PK ! څ. . README.md
# Aria2p
[![pipeline status](https://gitlab.com/pawamoy/aria2p/badges/master/pipeline.svg)](https://gitlab.com/pawamoy/aria2p/commits/master)
[![coverage report](https://gitlab.com/pawamoy/aria2p/badges/master/coverage.svg)](https://gitlab.com/pawamoy/aria2p/commits/master)
[![documentation](https://img.shields.io/readthedocs/aria2p.svg?style=flat)](https://aria2p.readthedocs.io/en/latest/index.html)
[![pypi version](https://img.shields.io/pypi/v/aria2p.svg)](https://pypi.org/project/aria2p/)
Command-line tool and Python library to interact with an [`aria2c`][1] daemon process through JSON-RPC.
To avoid confusion:
- [*aria2*][1] is a lightweight multi-protocol & multi-source, cross platform download utility operated in command-line.
It supports HTTP/HTTPS, FTP, SFTP, BitTorrent and Metalink.
- `aria2c` is the name of the command-line executable provided by *aria2*. It can act as a daemon.
- `aria2p` (`p` for Python) is a command-line client that can interact with an `aria2c` daemon.
It is not an official client. There are other Python packages allowing you to interact with an `aria2c` daemon.
These other packages do not offer enough usability (in my opinion), this is why I'm developing `aria2p`.
**Purpose**: `aria2c` can run in the foreground, for one-time downloads, or in the background, as a daemon.
This is where `aria2p` intervenes: when an instance of `aria2c` is running in the background with RPC mode enabled,
`aria2p` will be able to communicate with it to add downloads to the queue, remove, pause or resume them, etc.
RPC mode is enabled with the `--enable-rpc` option of `aria2c`. RPC stands for [Remote Procedure Call][2].
Although `aria2c` supports both JSON-RPC and XML-RPC protocols, `aria2p` **works with JSON only** (not XML).
More information about how to configure `aria2c` to run as a daemon with RPC mode enabled
can be found in the documentation at https://aria2p.readthedocs.io/en/latest.
## Requirements
`aria2p` requires Python 3.6 or above.
To install Python 3.6, I recommend using pyenv
.
```bash
# install pyenv
git clone https://github.com/pyenv/pyenv ~/.pyenv
# setup pyenv (you should also put these three lines in .bashrc or similar)
export PATH="${HOME}/.pyenv/bin:${PATH}"
export PYENV_ROOT="${HOME}/.pyenv"
eval "$(pyenv init -)"
# install Python 3.6
pyenv install 3.6.8
# make it available globally
pyenv global system 3.6.8
```
You must also install [*aria2*][1]. On systems with `apt-get`:
```bash
sudo apt-get install aria2
```
[1]: https://github.com/aria2/aria2
[2]: https://en.wikipedia.org/wiki/Remote_procedure_call
## Installation
With `pip`:
```bash
python3.6 -m pip install aria2p
```
With [`pipx`](https://github.com/cs01/pipx):
```bash
# install pipx with the recommended method
curl https://raw.githubusercontent.com/cs01/pipx/master/get-pipx.py | python3
pipx install --python python3.6 aria2p
```
## Usage (as a library)
**This library is still a work in progress. More examples will be added later.
In the meantime, you can read the [Reference section](https://aria2p.readthedocs.io/en/latest/reference.html) on the official documentation.**
```python
import aria2p
# initialization, these are the default values
aria2 = aria2p.API(
aria2p.Client(
host="http://localhost",
port=6800,
secret=""
)
)
# list downloads
downloads = aria2.get_downloads()
for download in downloads:
print(download.name, download.download_speed)
# add downloads
magnet_uri = "magnet:?xt=urn:..."
download = aria2.add_magnet(magnet_uri)
```
## Usage (command-line)
```
usage: aria2p [GLOBAL_OPTS...] COMMAND [COMMAND_OPTS...]
Command-line tool and Python library to interact with an `aria2c` daemon
process through JSON-RPC.
Global options:
-h, --help Show this help message and exit. Commands also accept
the -h/--help option.
-p PORT, --port PORT Port to use to connect to the remote server.
-H HOST, --host HOST Host address for the remote server.
-s SECRET, --secret SECRET
Secret token to use to connect to the remote server.
Commands:
add-magnet Add a download with a Magnet URI.
add-metalink Add a download with a Metalink file.
add-torrent Add a download with a Torrent file.
autopurge (autoclear)
Automatically purge completed/removed/failed
downloads.
call Call a remote method through the JSON-RPC client.
pause Pause downloads.
purge (clear) Purge downloads.
pause-all Pause all downloads.
remove (rm) Remove downloads.
remove-all Remove all downloads.
resume Resume downloads.
resume-all Resume all downloads.
show Show the download progression.
```
Calling `aria2p` without any arguments will by default call the `show` command,
which displays the list of current downloads:
```
GID STATUS PROGRESS DOWN_SPEED UP_SPEED ETA NAME
```
There is no interactive mode yet,
but you can use `watch` combined with the `show` subcommand
to see how the downloads progress:
```bash
watch -t -n1 aria2p show
```
Commands:
- [`add-magnet`](#add-magnet)
- [`add-metalink`](#add-metalink)
- [`add-torrent`](#add-torrent)
- [`autopurge`](#autopurge)
- [`call`](#call)
- [`pause`](#pause)
- [`purge`](#purge)
- [`pause-all`](#pause-all)
- [`remove`](#remove)
- [`remove-all`](#remove-all)
- [`resume`](#resume)
- [`resume-all`](#resume-all)
- [`show`](#show)
### `add-magnet`
```
usage: aria2p add-magnet [-h] uri
Add a download with a Magnet URI.
positional arguments:
uri The magnet URI to use.
optional arguments:
-h, --help Show this help message and exit.
```
### `add-metalink`
```
usage: aria2p add-metalink [-h] metalink_file
Add a download with a Metalink file.
positional arguments:
metalink_file The path to the metalink file.
optional arguments:
-h, --help Show this help message and exit.
```
### `add-torrent`
```
usage: aria2p add-torrent [-h] torrent_file
Add a download with a Torrent file.
positional arguments:
torrent_file The path to the torrent file.
optional arguments:
-h, --help Show this help message and exit.
```
### `autopurge`
```
usage: aria2p autopurge [-h]
Automatically purge completed/removed/failed downloads.
optional arguments:
-h, --help Show this help message and exit.
```
### `call`
```
usage: aria2p call [-h] [-P PARAMS [PARAMS ...] | -J PARAMS] method
Call a remote method through the JSON-RPC client.
positional arguments:
method The method to call (case insensitive). Dashes and
underscores will be removed so you can use as many as
you want, or none. Prefixes like 'aria2.' or 'system.'
are also optional.
optional arguments:
-h, --help Show this help message and exit.
-P PARAMS [PARAMS ...], --params-list PARAMS [PARAMS ...]
Parameters as a list of strings.
-J PARAMS, --json-params PARAMS
Parameters as a JSON string. You should always wrap it
at least once in an array '[]'.
```
As explained in the help text,
the `method` can be the exact method name,
or just the name without the prefix.
It is case-insensitive, and dashes and underscores will be removed.
The following are all equivalent:
- `aria2.addUri`
- `aria2.adduri`
- `addUri`
- `ADDURI`
- `aria2.ADD-URI`
- `add_uri`
- `A-d_D-u_R-i` (yes it's valid)
- `A---R---I---A---2.a__d__d__u__r__i` (I think you got it)
- and even more ugly forms...
#### Examples
List all available methods.
*This example uses [`jq`](https://github.com/stedolan/jq).*
```console
$ aria2p call listmethods | jq
[
"aria2.addUri",
"aria2.addTorrent",
"aria2.getPeers",
"aria2.addMetalink",
"aria2.remove",
"aria2.pause",
"aria2.forcePause",
"aria2.pauseAll",
"aria2.forcePauseAll",
"aria2.unpause",
"aria2.unpauseAll",
"aria2.forceRemove",
"aria2.changePosition",
"aria2.tellStatus",
"aria2.getUris",
"aria2.getFiles",
"aria2.getServers",
"aria2.tellActive",
"aria2.tellWaiting",
"aria2.tellStopped",
"aria2.getOption",
"aria2.changeUri",
"aria2.changeOption",
"aria2.getGlobalOption",
"aria2.changeGlobalOption",
"aria2.purgeDownloadResult",
"aria2.removeDownloadResult",
"aria2.getVersion",
"aria2.getSessionInfo",
"aria2.shutdown",
"aria2.forceShutdown",
"aria2.getGlobalStat",
"aria2.saveSession",
"system.multicall",
"system.listMethods",
"system.listNotifications"
]
```
List the GIDs (identifiers) of all active downloads.
*Note that we must give the parameters as a JSON string.*
```console
$ aria2p call tellactive -J '[["gid"]]'
[{"gid": "b686cad55029d4df"}, {"gid": "4b39a1ad8fd94e26"}, {"gid": "9d331cc4b287e5df"}, {"gid": "8c9de0df753a5195"}]
```
Pause a download using its GID.
*Note that when a single string argument is required, it can be passed directly with `-p`.*
```console
$ aria2p call pause -P b686cad55029d4df
"b686cad55029d4df"
```
Add a download using magnet URIs.
*This example uses `jq -r` to remove the quotation marks around the result.*
```console
$ aria2p call adduri -J '[["magnet:?xt=urn:..."]]' | jq -r
4b39a1ad8fd94e26f
```
Purge download results (remove completed downloads from the list).
```console
$ aria2p call purge_download_result
"OK"
```
### `pause`
```
usage: aria2p pause [-h] [-f] gids [gids ...]
Pause downloads.
positional arguments:
gids The GIDs of the downloads to pause.
optional arguments:
-h, --help Show this help message and exit.
-f, --force Pause without contacting servers first.
```
### `purge`
```
usage: aria2p purge [-h] [gids [gids ...]]
Purge downloads.
positional arguments:
gids The GIDs of the downloads to purge.
optional arguments:
-h, --help Show this help message and exit.
```
### `pause-all`
```
usage: aria2p pause-all [-h] [-f]
Pause all downloads.
optional arguments:
-h, --help Show this help message and exit.
-f, --force Pause without contacting servers first.
```
### `remove`
```
usage: aria2p remove [-h] [-f] gids [gids ...]
Remove downloads.
positional arguments:
gids The GIDs of the downloads to remove.
optional arguments:
-h, --help Show this help message and exit.
-f, --force Remove without contacting servers first.
```
### `remove-all`
```
usage: aria2p remove-all [-h] [-f]
Remove all downloads.
optional arguments:
-h, --help Show this help message and exit.
-f, --force Remove without contacting servers first.
```
### `resume`
```
usage: aria2p resume [-h] gids [gids ...]
Resume downloads.
positional arguments:
gids The GIDs of the downloads to resume.
optional arguments:
-h, --help Show this help message and exit.
```
### `resume-all`
```
usage: aria2p resume-all [-h]
Resume all downloads.
optional arguments:
-h, --help Show this help message and exit.
```
### `show`
```
usage: aria2p show [-h]
Show the download progression.
optional arguments:
-h, --help Show this help message and exit.
```
## Troubleshoot
1. Error outputs like below when using `aria2p` as a Python library:
```
requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=6800): Max retries exceeded with url: /jsonrpc (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 61] Connection refused',))
```
solution: `aria2c` needs to be up and running first.
PK ! * aria2p/__init__.py"""
Aria2p package.
This package provides a command-line tool and a Python library to interact with an `aria2c` daemon process through
JSON-RPC.
If you read this message, you probably want to learn about the library and not the command-line tool:
please refer to the README.md included in this package to get the link to the official documentation.
"""
from .api import API
from .client import Client, ClientException
from .downloads import BitTorrent, Download, File
from .options import Options
from .stats import Stats
__all__ = ["API", "ClientException", "Client", "Download", "BitTorrent", "File", "Options", "Stats"]
# TODO: write aria2, aria2c, Aria2, Aria2c consistently
# TODO: write Torrent, torrent, Metalink, metalink, BitTorrent... consistently
# TODO: write all docstrings
PK ! \逊 aria2p/__main__.py"""
Entry-point module, in case you use `python -maria2p`.
Why does this file exist, and why __main__? For more info, read:
- https://www.python.org/dev/peps/pep-0338/
- https://docs.python.org/2/using/cmdline.html#cmdoption-m
- https://docs.python.org/3/using/cmdline.html#cmdoption-m
"""
import sys
from aria2p.cli import main
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
PK ! BC C
aria2p/api.py"""
This module defines the API class, which makes use of a JSON-RPC client to provide higher-level methods to
interact easily with a remote aria2c process.
"""
from base64 import b64encode
from .client import Client, ClientException
from .downloads import Download
from .options import Options
from .stats import Stats
class API:
"""
A class providing high-level methods to interact with a remote aria2c process.
This class is instantiated with a reference to a :class:`aria2p.Client` instance. It then uses this client
to call remote procedures, or remote methods. The client methods reflect exactly what aria2c is providing
through JSON-RPC, while this class's methods allow for easier / faster control of the remote process. It also
wraps the information the client retrieves in Python object, like :class:`aria2p.Download`, allowing for
even more Pythonic interactions, without worrying about payloads, responses, JSON, etc..
"""
def __init__(self, client=None):
"""
Initialization method.
Args:
json_rpc_client (:class:`aria2p.Client`): an instance of the ``JSONRPCClient`` class.
"""
if client is None:
client = Client()
self.client = client
def add_magnet(self, magnet_uri, options=None, position=None):
"""
Add a download with a Magnet URI.
Args:
magnet_uri (str): the Magnet URI.
options (:class:`aria2p.Options` or dict): an instance of the ``Options`` class or a dictionary
containing Aria2c options to create the download with.
position (int): the position where to insert the new download in the queue. Start at 0 (top).
Returns:
:class:`aria2p.Download` instance: the newly created download object.
"""
if options is None:
options = {}
if isinstance(options, Options):
client_options = options.get_struct()
else:
client_options = options
gid = self.client.add_uri([magnet_uri], client_options, position)
return self.get_download(gid)
def add_torrent(self, torrent_file_path, uris=None, options=None, position=None):
"""
Add a download with a Torrent file (usually .torrent extension).
Args:
torrent_file_path (str/Path): the path to the Torrent file.
uris (list of str): a list of URIs used for Web-seeding.
options (:class:`aria2p.Options` or dict): an instance of the ``Options`` class or a dictionary
containing Aria2c options to create the download with.
position (int): the position where to insert the new download in the queue. Start at 0 (top).
Returns:
:class:`aria2p.Download` instance: the newly created download object.
"""
if uris is None:
uris = []
if options is None:
options = {}
if isinstance(options, Options):
client_options = options.get_struct()
else:
client_options = options
with open(torrent_file_path, "rb") as stream:
torrent_contents = stream.read()
encoded_contents = b64encode(torrent_contents).decode("utf8")
gid = self.client.add_torrent(encoded_contents, uris, client_options, position)
return self.get_download(gid)
def add_metalink(self, metalink_file_path, options=None, position=None):
"""
Add a download with a Metalink file.
Args:
metalink_file_path (str/Path): the path to the Metalink file.
options (:class:`aria2p.Options` or dict): an instance of the ``Options`` class or a dictionary
containing Aria2c options to create the download with.
position (int): the position where to insert the new download in the queue. Start at 0 (top).
Returns:
:class:`aria2p.Download` instance: the newly created download object.
"""
if options is None:
options = {}
if isinstance(options, Options):
client_options = options.get_struct()
else:
client_options = options
with open(metalink_file_path, "rb") as stream:
metalink_contents = stream.read()
encoded_contents = b64encode(metalink_contents).decode("utf8")
gids = self.client.add_metalink(encoded_contents, client_options, position)
return self.get_downloads(gids)
def add_uris(self, uris, options=None, position=None):
"""
Add a download with a URL (or more).
Args:
uris (list of str): a list of URIs that point to the same resource.
options (:class:`aria2p.Options` or dict): an instance of the ``Options`` class or a dictionary
containing Aria2c options to create the download with.
position (int): the position where to insert the new download in the queue. Start at 0 (top).
Returns:
:class:`aria2p.Download` instance: the newly created download object.
"""
if options is None:
options = {}
if isinstance(options, Options):
client_options = options.get_struct()
else:
client_options = options
gid = self.client.add_uri(uris, client_options, position)
return self.get_download(gid)
def search(self, patterns):
"""
Not implemented.
Search and return :class:`aria2p.Download` object based on multiple patterns.
Args:
patterns (list of dict): the patterns used to filter the download list.
Returns:
list of :class:`aria2p.Download` instances: the download objects matching the patterns.
"""
# gid
# status
# totalLength
# completedLength
# uploadLength
# bitfield
# downloadSpeed
# uploadSpeed
# infoHash
# numSeeders
# seeder
# pieceLength
# numPieces
# connections
# errorCode
# errorMessage
# followedBy
# following
# belongsTo
# dir
# files
# bittorrent
# announceList
# comment
# creationDate
# mode
# info
# name
# verifiedLength
# verifyIntegrityPending
raise NotImplementedError
def get_download(self, gid):
"""
Get a :class:`aria2p.Download` object thanks to its GID.
Args:
gid (str): the GID of the download to get.
Returns:
:class:`aria2p.Download` instance: the retrieved download object.
"""
return Download(self, self.client.tell_status(gid))
def get_downloads(self, gids=None):
"""
Get a list :class:`aria2p.Download` object thanks to their GIDs.
Args:
gids (list of str): the GIDs of the downloads to get. If None, return all the downloads.
Returns:
list of :class:`aria2p.Download` instances: the retrieved download objects.
"""
downloads = []
if gids:
for gid in gids:
downloads.append(Download(self, self.client.tell_status(gid)))
else:
structs = []
structs.extend(self.client.tell_active())
structs.extend(self.client.tell_waiting(0, 1000))
structs.extend(self.client.tell_stopped(0, 1000))
downloads = [Download(self, struct) for struct in structs]
return downloads
def move(self, download, pos):
"""
Move a download in the queue, relatively to its current position.
Args:
download (:class:`aria2p.Download`): the download object to move.
pos (int): the relative position (1 to move down, -1 to move up, -2 to move up two times, etc.).
Returns:
int: The new position of the download.
"""
return self.client.change_position(download.gid, pos, "POS_CUR")
def move_to(self, download, pos):
"""
Move a download in the queue, with absolute positioning.
Args:
download (:class:`aria2p.Download`): the download object to move.
pos (int): the absolute position in the queue where to move the download. 0 for top, -1 for bottom.
Returns:
int: The new position of the download.
"""
if pos < 0:
how = "POS_END"
pos = -pos
else:
how = "POS_SET"
return self.client.change_position(download.gid, pos, how)
def move_up(self, download, pos=1):
"""
Move a download up in the queue.
Args:
download (:class:`aria2p.Download`): the download object to move.
pos (int): number of times to move up. With negative values, will move down (use move or move_down instead).
Returns:
int: The new position of the download.
"""
return self.client.change_position(download.gid, -pos, "POS_CUR")
def move_down(self, download, pos=1):
"""
Move a download down in the queue.
Args:
download (:class:`aria2p.Download`): the download object to move.
pos (int): number of times to move down. With negative values, will move up (use move or move_up instead).
Returns:
int: The new position of the download.
"""
return self.client.change_position(download.gid, pos, "POS_CUR")
def move_to_top(self, download):
"""
Move a download to the top of the queue.
Args:
download (:class:`aria2p.Download`): the download object to move.
Returns:
int: The new position of the download.
"""
return self.client.change_position(download.gid, 0, "POS_SET")
def move_to_bottom(self, download):
"""
Move a download to the bottom of the queue.
Args:
download (:class:`aria2p.Download`): the download object to move.
Returns:
int: The new position of the download.
"""
return self.client.change_position(download.gid, 0, "POS_END")
def remove(self, downloads, force=False):
"""
Remove the given downloads from the list.
Args:
downloads (list of :class:`aria2p.Download`): the list of downloads to remove.
force (bool): whether to force the removal or not.
Returns:
list of bool: Success or failure of the operation for each given download.
"""
# TODO: batch/multicall candidate
if force:
remove_func = self.client.force_remove
else:
remove_func = self.client.remove
result = []
for download in downloads:
try:
removed_gid = remove_func(download.gid)
except ClientException as e:
result.append(e)
else:
result.append(True)
self.client.remove_download_result(download.gid)
if removed_gid != download.gid:
self.client.remove_download_result(removed_gid)
return result
def remove_all(self, force=False):
"""
Remove all downloads from the list.
Args:
force (bool): whether to force the removal or not.
Returns:
bool: Success or failure of the operation to remove all downloads.
"""
return all(self.remove(self.get_downloads(), force=force))
def pause(self, downloads, force=False):
"""
Remove the given downloads from the list.
Args:
downloads (list of :class:`aria2p.Download`): the list of downloads to remove.
force (bool): whether to pause immediately without contacting servers or not.
Returns:
list of bool: Success or failure of the operation for each given download.
"""
# TODO: batch/multicall candidate
if force:
pause_func = self.client.force_pause
else:
pause_func = self.client.pause
result = []
for download in downloads:
try:
pause_func(download.gid)
except ClientException as e:
result.append(e)
else:
result.append(True)
return result
def pause_all(self, force=False):
"""
Remove the given downloads from the list.
Args:
force (bool): whether to pause immediately without contacting servers or not.
Returns:
bool: Success or failure of the operation to pause all downloads.
"""
# if force:
# pause_func = self.client.force_pause_all
# else:
# pause_func = self.client.pause_all
# return pause_func() == "OK"
return all(self.pause(self.get_downloads(), force=force))
def resume(self, downloads):
"""
Resume (unpause) the given downloads.
Args:
downloads (list of :class:`aria2p.Download`): the list of downloads to resume.
Returns:
list of bool: Success or failure of the operation for each given download.
"""
# TODO: batch/multicall candidate
result = []
for download in downloads:
try:
self.client.unpause(download.gid)
except ClientException as e:
result.append(e)
else:
result.append(True)
return result
def resume_all(self):
"""
Resume (unpause) all downloads.
Returns:
bool: Success or failure of the operation to resume all downloads.
"""
return all(self.resume(self.get_downloads()))
def autopurge(self):
"""
Purge completed, removed or failed downloads from the queue.
Returns:
bool: Success or failure of the operation.
"""
return self.client.purge_download_result()
def purge(self, downloads):
"""
Purge given downloads from the queue.
Returns:
list of bool: Success or failure of the operation for each download.
"""
result = []
for download in downloads:
try:
self.client.remove_download_result(download.gid)
except ClientException as e:
result.append(e)
else:
result.append(True)
return result
def get_options(self, downloads):
"""
Get options for each of the given downloads.
Args:
downloads (list of :class:`aria2p.Download`): the list of downloads to get the options of.
Returns:
list of :class:`aria2p.Options`: options object for each given download.
"""
# TODO: batch/multicall candidate
options = []
for download in downloads:
options.append(Options(self, self.client.get_option(download.gid), download))
return options
def get_global_options(self):
"""
Get the global options.
Returns:
:class:`aria2p.Options` instance: the global Aria2c options.
"""
return Options(self, self.client.get_global_option())
def set_options(self, options, downloads):
"""
Set options for specific downloads.
Args:
options (:class:`aria2p.Options` or dict): an instance of the ``Options`` class or a dictionary
containing Aria2c options to create the download with.
downloads (list of :class:`aria2p.Download`): the list of downloads to set the options for.
Returns:
list of bool: Success or failure of the operation for changing options for each given download.
"""
if isinstance(options, Options):
client_options = options.get_struct()
else:
client_options = options
# TODO: batch/multicall candidate
results = []
for download in downloads:
results.append(self.client.change_option(download.gid, client_options) == "OK")
return results
def set_global_options(self, options):
"""
Set global options.
Args:
options (:class:`aria2p.Options` or dict): an instance of the ``Options`` class or a dictionary
containing Aria2c options to create the download with.
Returns:
bool: Success or failure of the operation for changing global options.
"""
if isinstance(options, Options):
client_options = options.get_struct()
else:
client_options = options
return self.client.change_global_option(client_options) == "OK"
def get_stats(self):
"""
Get the stats of the remote Aria2c process.
Returns:
:class:`aria2p.Stats` instance: the global stats returned by the remote process.
"""
return Stats(self.client.get_global_stat())
PK ! f=n3 n3
aria2p/cli.py"""
Module that contains the command line application.
Why does this file exist, and why not put this in __main__?
You might be tempted to import things from __main__ later,
but that will cause problems: the code will get executed twice:
- When you run `python -maria2p` python will execute
``__main__.py`` as a script. That means there won't be any
``aria2p.__main__`` in ``sys.modules``.
- When you import __main__ it will get executed again (as a module) because
there's no ``aria2p.__main__`` in ``sys.modules``.
Also see (1) from http://click.pocoo.org/5/setuptools/#setuptools-integration
"""
import argparse
import json
import sys
import requests
from aria2p import Download
from .api import API
from .client import DEFAULT_HOST, DEFAULT_PORT, Client, ClientException
# ============ MAIN FUNCTION ============ #
def main(args=None):
"""The main function, which is executed when you type ``aria2p`` or ``python -m aria2p``."""
parser = get_parser()
args = parser.parse_args(args=args)
kwargs = args.__dict__
api = API(Client(host=kwargs.pop("host"), port=kwargs.pop("port"), secret=kwargs.pop("secret")))
# Warn if no aria2 daemon process seems to be running
try:
api.client.get_version()
except requests.ConnectionError as e:
print(f"[ERROR] {e}", file=sys.stderr)
print(file=sys.stderr)
print("Please make sure that an instance of aria2c is running with RPC mode enabled,", file=sys.stderr)
print("and that you have provided the right host, port and secret token.", file=sys.stderr)
print("More information at https://aria2p.readthedocs.io/en/latest.", file=sys.stderr)
return 2
subcommands = {
None: subcommand_show,
"show": subcommand_show,
"call": subcommand_call,
"add-magnet": subcommand_add_magnet,
"add-torrent": subcommand_add_torrent,
"add-metalink": subcommand_add_metalink,
"pause": subcommand_pause,
"pause-all": subcommand_pause_all,
"resume": subcommand_resume,
"resume-all": subcommand_resume_all,
"remove": subcommand_remove,
"remove-all": subcommand_remove_all,
"purge": subcommand_purge,
"autopurge": subcommand_autopurge,
}
subcommand = kwargs.pop("subcommand")
try:
return subcommands.get(subcommand)(api, **kwargs)
except ClientException as e:
print(e.message)
return e.code
def get_parser():
"""Return a parser for the command-line options and arguments."""
usage = "%(prog)s [GLOBAL_OPTS...] COMMAND [COMMAND_OPTS...]"
description = "Command-line tool and Python library to interact with an `aria2c` daemon process through JSON-RPC."
parser = argparse.ArgumentParser(add_help=False, usage=usage, description=description, prog="aria2p")
main_help = "Show this help message and exit. Commands also accept the -h/--help option."
subcommand_help = "Show this help message and exit."
global_options = parser.add_argument_group(title="Global options")
global_options.add_argument("-h", "--help", action="help", help=main_help)
global_options.add_argument(
"-p", "--port", dest="port", default=DEFAULT_PORT, type=int, help="Port to use to connect to the remote server."
)
global_options.add_argument(
"-H", "--host", dest="host", default=DEFAULT_HOST, help="Host address for the remote server."
)
global_options.add_argument(
"-s", "--secret", dest="secret", default="", help="Secret token to use to connect to the remote server."
)
# ========= SUBPARSERS ========= #
subparsers = parser.add_subparsers(dest="subcommand", title="Commands", metavar="", prog="aria2p")
def subparser(command, text, **kwargs):
p = subparsers.add_parser(command, add_help=False, help=text, description=text, **kwargs)
p.add_argument("-h", "--help", action="help", help=subcommand_help)
return p
add_magnet_parser = subparser("add-magnet", "Add a download with a Magnet URI.")
add_metalink_parser = subparser("add-metalink", "Add a download with a Metalink file.")
add_torrent_parser = subparser("add-torrent", "Add a download with a Torrent file.")
subparser("autopurge", "Automatically purge completed/removed/failed downloads.", aliases=["autoclear"])
call_parser = subparser("call", "Call a remote method through the JSON-RPC client.")
pause_parser = subparser("pause", "Pause downloads.")
purge_parser = subparser("purge", "Purge downloads.", aliases=["clear"])
pause_all_parser = subparser("pause-all", "Pause all downloads.")
remove_parser = subparser("remove", "Remove downloads.", aliases=["rm"])
remove_all_parser = subparser("remove-all", "Remove all downloads.")
resume_parser = subparser("resume", "Resume downloads.")
subparser("resume-all", "Resume all downloads.")
subparser("show", "Show the download progression.")
# ========= CALL PARSER ========= #
call_parser.add_argument(
"method",
help=(
"The method to call (case insensitive). "
"Dashes and underscores will be removed so you can use as many as you want, or none. "
"Prefixes like 'aria2.' or 'system.' are also optional."
),
)
call_parser_mxg = call_parser.add_mutually_exclusive_group()
call_parser_mxg.add_argument(
"-P", "--params-list", dest="params", nargs="+", help="Parameters as a list of strings."
)
call_parser_mxg.add_argument(
"-J",
"--json-params",
dest="params",
help="Parameters as a JSON string. You should always wrap it at least once in an array '[]'.",
)
# ========= ADD MAGNET PARSER ========= #
add_magnet_parser.add_argument("uri", help="The magnet URI to use.")
# ========= ADD TORRENT PARSER ========= #
add_torrent_parser.add_argument("torrent_file", help="The path to the torrent file.")
# ========= ADD METALINK PARSER ========= #
add_metalink_parser.add_argument("metalink_file", help="The path to the metalink file.")
# ========= PAUSE PARSER ========= #
pause_parser.add_argument("gids", nargs="+", help="The GIDs of the downloads to pause.")
pause_parser.add_argument(
"-f", "--force", dest="force", action="store_true", help="Pause without contacting servers first."
)
# ========= PAUSE ALL PARSER ========= #
pause_all_parser.add_argument(
"-f", "--force", dest="force", action="store_true", help="Pause without contacting servers first."
)
# ========= RESUME PARSER ========= #
resume_parser.add_argument("gids", nargs="+", help="The GIDs of the downloads to resume.")
# ========= REMOVE PARSER ========= #
remove_parser.add_argument("gids", nargs="+", help="The GIDs of the downloads to remove.")
remove_parser.add_argument(
"-f", "--force", dest="force", action="store_true", help="Remove without contacting servers first."
)
# ========= REMOVE ALL PARSER ========= #
remove_all_parser.add_argument(
"-f", "--force", dest="force", action="store_true", help="Remove without contacting servers first."
)
# ========= PURGE PARSER ========= #
purge_parser.add_argument("gids", nargs="*", help="The GIDs of the downloads to purge.")
# TODO: when API is ready
# info_parser = subparsers.add_parser("info", help="Show information about downloads.")
# info_parser_mxg = info_parser.add_mutually_exclusive_group()
# info_parser_mxg.add_argument("gids", nargs="+")
# info_parser_mxg.add_argument("-a", "--all", dest="select_all", action="store_true")
# TODO: add --format, --fields
# TODO: when API is ready
# list_parser = subparsers.add_parser("list", help="List downloads.", aliases=["ls"])
# list_parser.add_argument("-f", "--format", dest="format")
# list_parser.add_argument("-s", "--sort", dest="sort")
# TODO: add --hide-metadata
# TODO: when API is ready
# search_parser = subparsers.add_parser("search", help="Search downloads using patterns or regular expressions.")
# search_parser.add_argument("-L", "--literal", dest="literal", action="store_true")
# TODO: add options (--set), stats, move-files, save-session, shutdown
return parser
# ============ SHOW SUBCOMMAND ============ #
def subcommand_show(api):
downloads = api.get_downloads()
print(
f"{'GID':<17} "
f"{'STATUS':<9} "
f"{'PROGRESS':>8} "
f"{'DOWN_SPEED':>12} "
f"{'UP_SPEED':>12} "
f"{'ETA':>8} "
f"NAME"
)
for download in downloads:
print(
f"{download.gid:<17} "
f"{download.status:<9} "
f"{download.progress_string():>8} "
f"{download.download_speed_string():>12} "
f"{download.upload_speed_string():>12} "
f"{download.eta_string():>8} "
f"{download.name}"
)
# ============ CALL SUBCOMMAND ============ #
def subcommand_call(api, method, params):
method = get_method(method)
if method is None:
print(f"[ERROR] call: Unknown method {method}.", file=sys.stderr)
print(file=sys.stderr)
print("Run '{sys.argv[0]} -m listmethods' to list the available methods.", file=sys.stderr)
return 1
if isinstance(params, str):
params = json.loads(params)
elif params is None:
params = []
response = api.client.call(method, params)
print(json.dumps(response))
return 0
def get_method(name, default=None):
"""Return the actual method name from a differently formatted name."""
methods = {}
for method in Client.METHODS:
methods[method.lower()] = method
methods[method.split(".")[1].lower()] = method
name = name.lower()
name = name.replace("-", "")
name = name.replace("_", "")
return methods.get(name, default)
# ============ ADD MAGNET SUBCOMMAND ============ #
def subcommand_add_magnet(api, uri):
new_download = api.add_magnet(uri)
print(f"Created download {new_download.gid}")
return 0
# ============ ADD TORRENT SUBCOMMAND ============ #
def subcommand_add_torrent(api, torrent_file):
new_download = api.add_torrent(torrent_file)
print(f"Created download {new_download.gid}")
return 0
# ============ ADD METALINK SUBCOMMAND ============ #
def subcommand_add_metalink(api: API, metalink_file):
new_download = api.add_metalink(metalink_file)
print(f"Created download {new_download.gid}")
return 0
# ============ PAUSE SUBCOMMAND ============ #
def subcommand_pause(api: API, gids, force=False):
downloads = [Download(api, {"gid": gid}) for gid in gids]
result = api.pause(downloads, force=force)
if all(result):
return 0
for item in result:
if isinstance(item, ClientException):
print(item)
return 1
# ============ PAUSE ALL SUBCOMMAND ============ #
def subcommand_pause_all(api: API, force=False):
if api.pause_all(force=force):
return 0
return 1
# ============ RESUME SUBCOMMAND ============ #
def subcommand_resume(api: API, gids):
downloads = [Download(api, {"gid": gid}) for gid in gids]
result = api.resume(downloads)
if all(result):
return 0
for item in result:
if isinstance(item, ClientException):
print(item)
return 1
# ============ RESUME ALL SUBCOMMAND ============ #
def subcommand_resume_all(api: API):
if api.resume_all():
return 0
return 1
# ============ REMOVE SUBCOMMAND ============ #
def subcommand_remove(api: API, gids, force=False):
downloads = [Download(api, {"gid": gid}) for gid in gids]
result = api.remove(downloads, force=force)
if all(result):
return 0
for item in result:
if isinstance(item, ClientException):
print(item)
return 1
# ============ REMOVE ALL SUBCOMMAND ============ #
def subcommand_remove_all(api: API, force=False):
if api.remove_all(force=force):
return 0
return 1
# ============ PURGE SUBCOMMAND ============ #
def subcommand_purge(api: API, gids):
downloads = [Download(api, {"gid": gid}) for gid in gids]
result = api.purge(downloads)
if all(result):
return 0
for item in result:
if isinstance(item, ClientException):
print(item)
return 1
# ============ AUTOPURGE SUBCOMMAND ============ #
def subcommand_autopurge(api: API):
if api.autopurge():
return 0
return 1
# ============ INFO SUBCOMMAND ============ #
# def subcommand_info(api: API, gids, select_all=False):
# if select_all:
# downloads = api.get_downloads()
# else:
# downloads = api.get_downloads(gids)
#
# api.info(downloads)
# return 0
# ============ LIST SUBCOMMAND ============ #
# def subcommand_list(api: API, list_format=None, sort=None):
# api.list(list_format=list_format, sort=sort)
# return 0
# ============ SEARCH SUBCOMMAND ============ #
# def subcommand_search(api: API, ):
# api.search()
# return 0
PK ! aria2p/client.py"""
This module defines the ClientException and Client classes, which are used to communicate with a remote aria2c
process through the JSON-RPC protocol.
"""
import json
import requests
DEFAULT_ID = -1
DEFAULT_HOST = "http://localhost"
DEFAULT_PORT = 6800
JSONRPC_PARSER_ERROR = -32700
JSONRPC_INVALID_REQUEST = -32600
JSONRPC_METHOD_NOT_FOUND = -32601
JSONRPC_INVALID_PARAMS = -32602
JSONRPC_INTERNAL_ERROR = -32603
JSONRPC_CODES = {
JSONRPC_PARSER_ERROR: "Invalid JSON was received by the server.",
JSONRPC_INVALID_REQUEST: "The JSON sent is not a valid Request object.",
JSONRPC_METHOD_NOT_FOUND: "The method does not exist / is not available.",
JSONRPC_INVALID_PARAMS: "Invalid method parameter(s).",
JSONRPC_INTERNAL_ERROR: "Internal JSON-RPC error.",
}
class ClientException(Exception):
"""An exception specific to JSON-RPC errors."""
def __init__(self, code, message):
if code in JSONRPC_CODES:
message = f"{JSONRPC_CODES[code]}\n{message}"
self.code = code
self.message = message
def __str__(self):
return self.message
def __bool__(self):
return False
class Client:
"""
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.
"""
ADD_URI = "aria2.addUri"
ADD_TORRENT = "aria2.addTorrent"
ADD_METALINK = "aria2.addMetalink"
REMOVE = "aria2.remove"
FORCE_REMOVE = "aria2.forceRemove"
PAUSE = "aria2.pause"
PAUSE_ALL = "aria2.pauseAll"
FORCE_PAUSE = "aria2.forcePause"
FORCE_PAUSE_ALL = "aria2.forcePauseAll"
UNPAUSE = "aria2.unpause"
UNPAUSE_ALL = "aria2.unpauseAll"
TELL_STATUS = "aria2.tellStatus"
GET_URIS = "aria2.getUris"
GET_FILES = "aria2.getFiles"
GET_PEERS = "aria2.getPeers"
GET_SERVERS = "aria2.getServers"
TELL_ACTIVE = "aria2.tellActive"
TELL_WAITING = "aria2.tellWaiting"
TELL_STOPPED = "aria2.tellStopped"
CHANGE_POSITION = "aria2.changePosition"
CHANGE_URI = "aria2.changeUri"
GET_OPTION = "aria2.getOption"
CHANGE_OPTION = "aria2.changeOption"
GET_GLOBAL_OPTION = "aria2.getGlobalOption"
CHANGE_GLOBAL_OPTION = "aria2.changeGlobalOption"
GET_GLOBAL_STAT = "aria2.getGlobalStat"
PURGE_DOWNLOAD_RESULT = "aria2.purgeDownloadResult"
REMOVE_DOWNLOAD_RESULT = "aria2.removeDownloadResult"
GET_VERSION = "aria2.getVersion"
GET_SESSION_INFO = "aria2.getSessionInfo"
SHUTDOWN = "aria2.shutdown"
FORCE_SHUTDOWN = "aria2.forceShutdown"
SAVE_SESSION = "aria2.saveSession"
MULTICALL = "system.multicall"
LIST_METHODS = "system.listMethods"
LIST_NOTIFICATIONS = "system.listNotifications"
METHODS = [
ADD_URI,
ADD_TORRENT,
ADD_METALINK,
REMOVE,
FORCE_REMOVE,
PAUSE,
PAUSE_ALL,
FORCE_PAUSE,
FORCE_PAUSE_ALL,
UNPAUSE,
UNPAUSE_ALL,
TELL_STATUS,
GET_URIS,
GET_FILES,
GET_PEERS,
GET_SERVERS,
TELL_ACTIVE,
TELL_WAITING,
TELL_STOPPED,
CHANGE_POSITION,
CHANGE_URI,
GET_OPTION,
CHANGE_OPTION,
GET_GLOBAL_OPTION,
CHANGE_GLOBAL_OPTION,
GET_GLOBAL_STAT,
PURGE_DOWNLOAD_RESULT,
REMOVE_DOWNLOAD_RESULT,
GET_VERSION,
GET_SESSION_INFO,
SHUTDOWN,
FORCE_SHUTDOWN,
SAVE_SESSION,
MULTICALL,
LIST_METHODS,
LIST_NOTIFICATIONS,
]
def __init__(self, host=DEFAULT_HOST, port=DEFAULT_PORT, secret=""): # nosec
"""
Initialization method.
Args:
host (str): the remote process address.
port (int): the remote process port.
secret (str): the secret token.
"""
host = host.rstrip("/")
self.host = host
self.port = port
self.secret = secret
def __str__(self):
return self.server
@property
def server(self):
"""Property to return the full remote process / server address."""
return f"{self.host}:{self.port}/jsonrpc"
# utils
def call(self, method, params=None, msg_id=None, insert_secret=True):
"""
Call a single JSON-RPC method.
Args:
method (str): the method name. You can use the constant defined in :class:`aria2p.Client`.
params (list): a list of parameters.
msg_id (int/str): the ID of the call, sent back with the server's answer.
insert_secret (bool): 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).
"""
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}")
return self.res_or_raise(self.post(self.get_payload(method, params, msg_id=msg_id)))
def batch_call(self, calls, insert_secret=True):
"""
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
Args:
calls (list): a list of tuples composed of method name, parameters and ID.
insert_secret (bool): whether to insert the secret token in the parameters or not.
Returns:
list: the results for each call in the batch.
"""
payloads = []
for method, params, msg_id in calls:
params = self.get_params(*params)
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 = json.dumps(payloads)
responses = self.post(payload)
return [self.res_or_raise(resp) for resp in responses]
def multicall2(self, calls, insert_secret=True):
"""
An 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": ["2089b05ecca3d829"]},
{"methodName": client.REMOVE, "params": ["2fa07b6e85c40205"]},
]
With multicall2, you can reduce the verbosity:
[
(client.REMOVE, ["2089b05ecca3d829"]),
(client.REMOVE, ["2fa07b6e85c40205"]),
]
Note:
multicall2 is not part of the JSON-RPC protocol specification.
It is implemented here as a simple convenience method.
Args:
calls (list): list of tuples composed of method name and parameters.
insert_secret (bool): 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)
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 = self.get_payload(self.MULTICALL, [multicall_params])
return self.res_or_raise(self.post(payload))
def post(self, payload):
"""
Send a POST request to the server.
The response is a JSON string, which we then load as a Python object.
Args:
payload (dict): 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).json()
@staticmethod
def res_or_raise(response):
"""
Return the result of the response, or raise an error with code and message.
Args:
response (dict): 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 :class:`aria2p.ClientException` class.
"""
if "result" in response:
return response["result"]
raise ClientException(response["error"]["code"], response["error"]["message"])
@staticmethod
def get_payload(method, params=None, msg_id=None, as_json=True):
"""
Build a payload.
Args:
method (str): the method name. You can use the constant defined in :aria2p:`client.Client`.
params (list): the list of parameters.
msg_id (int/str): the ID of the call, sent back with the server's answer.
as_json (bool): whether to return the payload as a JSON-string or Python dictionary.
Returns:
"""
payload = {"jsonrpc": "2.0", "method": method}
if msg_id is not None:
payload["id"] = msg_id
else:
payload["id"] = DEFAULT_ID
if params:
payload["params"] = params
return json.dumps(payload) if as_json else payload
@staticmethod
def get_params(*args):
"""
Build the list of parameters.
This method simply removes the ``None`̀` values from the given arguments.
Args:
*args: list of parameters.
Returns:
A new list, with ``None``s filtered out.
"""
return [p for p in args if p is not None]
# aria2
def add_uri(self, uris, options=None, position=None):
"""
aria2.addUri([secret], uris[, options[, position]])
This method adds a new download. 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 is a struct and its members are pairs of option name and
value. See Options below for more details. 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. This
method returns the GID of the newly registered download.
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":"2089b05ecca3d829"}'
XML-RPC Example
The following example adds http://example.org/file:
>>> import xmlrpclib
>>> s = xmlrpclib.ServerProxy('http://localhost:6800/rpc')
>>> s.aria2.addUri(['http://example.org/file'])
'2089b05ecca3d829'
The following example adds a new download with two sources and some options:
>>> s.aria2.addUri(['http://example.org/file', 'http://mirror/file'], dict(dir="/tmp"))
'd2703803b52216d1'
The following example adds a download and inserts it to the front of the queue:
>>> s.aria2.addUri(['http://example.org/file'], {}, 0)
'ca3d829cee549a4d'
"""
return self.call(self.ADD_URI, params=[uris, options, position])
def add_torrent(self, torrent, uris, options=None, position=None):
"""
aria2.addTorrent([secret], torrent[, uris[, options[, position]]])
This method adds a BitTorrent download by uploading a ".torrent" file. If you want to add a BitTorrent
Magnet URI, use the aria2.addUri() method instead. torrent must be a base64-encoded string containing
the contents of the ".torrent" file. 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 is a struct and its members are pairs of option name and value. See Options below
for more details. 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. This method returns the GID of the
newly registered download. 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.
The following examples add local file file.torrent.
JSON-RPC Example
>>> 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":"2089b05ecca3d829"}'
XML-RPC Example
>>> import xmlrpclib
>>> s = xmlrpclib.ServerProxy('http://localhost:6800/rpc')
>>> s.aria2.addTorrent(xmlrpclib.Binary(open('file.torrent', mode='rb').read()))
'2089b05ecca3d829'
"""
return self.call(self.ADD_TORRENT, [torrent, uris, options, position])
def add_metalink(self, metalink, options=None, position=None):
"""
aria2.addMetalink([secret], metalink[, options[, position]])
This method adds a Metalink download by uploading a ".metalink" file. metalink is a base64-encoded string
which contains the contents of the ".metalink" file. options is a struct and its members are pairs of
option name and value. See Options below for more details. 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. This method returns an array of GIDs of newly registered downloads. 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.
The following examples add local file file.meta4.
JSON-RPC Example
>>> 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":["2089b05ecca3d829"]}'
XML-RPC Example
>>> import xmlrpclib
>>> s = xmlrpclib.ServerProxy('http://localhost:6800/rpc')
>>> s.aria2.addMetalink(xmlrpclib.Binary(open('file.meta4', mode='rb').read()))
['2089b05ecca3d829']
"""
return self.call(self.ADD_METALINK, [metalink, options, position])
def remove(self, gid):
"""
aria2.remove([secret], gid)
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.
The following examples remove a download with GID#2089b05ecca3d829.
JSON-RPC Example
>>> import urllib2, json
>>> jsonreq = json.dumps({'jsonrpc':'2.0', 'id':'qwer',
... 'method':'aria2.remove',
... 'params':['2089b05ecca3d829']})
>>> c = urllib2.urlopen('http://localhost:6800/jsonrpc', jsonreq)
>>> c.read()
'{"id":"qwer","jsonrpc":"2.0","result":"2089b05ecca3d829"}'
XML-RPC Example
>>> import xmlrpclib
>>> s = xmlrpclib.ServerProxy('http://localhost:6800/rpc')
>>> s.aria2.remove('2089b05ecca3d829')
'2089b05ecca3d829'
"""
return self.call(self.REMOVE, [gid])
def force_remove(self, gid):
"""
aria2.forceRemove([secret], gid)
This method removes the download denoted by gid. This method behaves just like aria2.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.
"""
return self.call(self.FORCE_REMOVE, [gid])
def pause(self, gid):
"""
aria2.pause([secret], gid)
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 aria2.unpause() method. This
method returns GID of paused download.
"""
return self.call(self.PAUSE, [gid])
def pause_all(self):
"""
aria2.pauseAll([secret])
This method is equal to calling aria2.pause() for every active/waiting download. This methods returns OK.
"""
return self.call(self.PAUSE_ALL)
def force_pause(self, gid):
"""
aria2.forcePause([secret], gid)
This method pauses the download denoted by gid. This method behaves just like aria2.pause() except that this
method pauses downloads without performing any actions which take time, such as contacting BitTorrent
trackers to unregister the download first.
"""
return self.call(self.FORCE_PAUSE, [gid])
def force_pause_all(self):
"""
aria2.forcePauseAll([secret])
This method is equal to calling aria2.forcePause() for every active/waiting download. This methods returns OK.
"""
return self.call(self.FORCE_PAUSE_ALL)
def unpause(self, gid):
"""
aria2.unpause([secret], gid)
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.
"""
return self.call(self.UNPAUSE, [gid])
def unpause_all(self):
"""
aria2.unpauseAll([secret])
This method is equal to calling aria2.unpause() for every active/waiting download. This methods returns OK.
"""
return self.call(self.UNPAUSE_ALL)
def tell_status(self, gid, keys=None):
"""
aria2.tellStatus([secret], gid[, keys])
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, aria2.tellStatus("2089b05ecca3d829", ["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 aria2.getFiles() method.
bittorrent
Struct which contains information retrieved from the .torrent (file). BitTorrent only.
It contains 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.
JSON-RPC Example
The following example gets information about a download with GID#2089b05ecca3d829:
>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps({'jsonrpc':'2.0', 'id':'qwer',
... 'method':'aria2.tellStatus',
... 'params':['2089b05ecca3d829']})
>>> 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'2089b05ecca3d829',
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':['2089b05ecca3d829',
... ['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'2089b05ecca3d829',
u'totalLength': u'34896138'}}
XML-RPC Example
The following example gets information about a download with GID#2089b05ecca3d829:
>>> import xmlrpclib
>>> from pprint import pprint
>>> s = xmlrpclib.ServerProxy('http://localhost:6800/rpc')
>>> r = s.aria2.tellStatus('2089b05ecca3d829')
>>> pprint(r)
{'bitfield': 'ffff80',
'completedLength': '34896138',
'connections': '0',
'dir': '/downloads',
'downloadSpeed': '0',
'errorCode': '0',
'files': [{'index': '1',
'length': '34896138',
'completedLength': '34896138',
'path': '/downloads/file',
'selected': 'true',
'uris': [{'status': 'used',
'uri': 'http://example.org/file'}]}],
'gid': '2089b05ecca3d829',
'numPieces': '17',
'pieceLength': '2097152',
'status': 'complete',
'totalLength': '34896138',
'uploadLength': '0',
'uploadSpeed': '0'}
The following example gets only specific keys:
>>> r = s.aria2.tellStatus('2089b05ecca3d829', ['gid', 'totalLength', 'completedLength'])
>>> pprint(r)
{'completedLength': '34896138', 'gid': '2089b05ecca3d829', 'totalLength': '34896138'}
"""
return self.call(self.TELL_STATUS, [gid, keys])
def get_uris(self, gid):
"""
aria2.getUris([secret], gid)
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.
JSON-RPC Example
>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps({'jsonrpc':'2.0', 'id':'qwer',
... 'method':'aria2.getUris',
... 'params':['2089b05ecca3d829']})
>>> 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'}]}
XML-RPC Example
>>> import xmlrpclib
>>> from pprint import pprint
>>> s = xmlrpclib.ServerProxy('http://localhost:6800/rpc')
>>> r = s.aria2.getUris('2089b05ecca3d829')
>>> pprint(r)
[{'status': 'used', 'uri': 'http://example.org/file'}]
"""
return self.call(self.GET_URIS, [gid])
def get_files(self, gid):
"""
aria2.getFiles([secret], gid)
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 aria2.tellStatus() method. This is because
completedLength in aria2.getFiles() only includes completed pieces. On the other hand,
completedLength in aria2.tellStatus() also includes partially completed pieces.
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 aria2.getUris()
method.
JSON-RPC Example
>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps({'jsonrpc':'2.0', 'id':'qwer',
... 'method':'aria2.getFiles',
... 'params':['2089b05ecca3d829']})
>>> 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'}]}]}
XML-RPC Example
>>> import xmlrpclib
>>> from pprint import pprint
>>> s = xmlrpclib.ServerProxy('http://localhost:6800/rpc')
>>> r = s.aria2.getFiles('2089b05ecca3d829')
>>> pprint(r)
[{'index': '1',
'length': '34896138',
'completedLength': '34896138',
'path': '/downloads/file',
'selected': 'true',
'uris': [{'status': 'used',
'uri': 'http://example.org/file'}]}]
"""
return self.call(self.GET_FILES, [gid])
def get_peers(self, gid):
"""
aria2.getPeers([secret], gid)
This method returns a list 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.
JSON-RPC Example
>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps({'jsonrpc':'2.0', 'id':'qwer',
... 'method':'aria2.getPeers',
... 'params':['2089b05ecca3d829']})
>>> 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'}]}
XML-RPC Example
>>> import xmlrpclib
>>> from pprint import pprint
>>> s = xmlrpclib.ServerProxy('http://localhost:6800/rpc')
>>> r = s.aria2.getPeers('2089b05ecca3d829')
>>> pprint(r)
[{'amChoking': 'true',
'bitfield': 'ffffffffffffffffffffffffffffffffffffffff',
'downloadSpeed': '10602',
'ip': '10.0.0.9',
'peerChoking': 'false',
'peerId': 'aria2%2F1%2E10%2E5%2D%87%2A%EDz%2F%F7%E6',
'port': '6881',
'seeder': 'true',
'uploadSpeed': '0'},
{'amChoking': 'false',
'bitfield': 'ffffeff0fffffffbfffffff9fffffcfff7f4ffff',
'downloadSpeed': '8654',
'ip': '10.0.0.30',
'peerChoking': 'false',
'peerId': 'bittorrent client758',
'port': '37842',
'seeder': 'false,
'uploadSpeed': '6890'}]
"""
return self.call(self.GET_PEERS, [gid])
def get_servers(self, gid):
"""
aria2.getServers([secret], gid)
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)
JSON-RPC Example
>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps({'jsonrpc':'2.0', 'id':'qwer',
... 'method':'aria2.getServers',
... 'params':['2089b05ecca3d829']})
>>> 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'}]}]}
XML-RPC Example
>>> import xmlrpclib
>>> from pprint import pprint
>>> s = xmlrpclib.ServerProxy('http://localhost:6800/rpc')
>>> r = s.aria2.getServers('2089b05ecca3d829')
>>> pprint(r)
[{'index': '1',
'servers': [{'currentUri': 'http://example.org/dl/file',
'downloadSpeed': '20285',
'uri': 'http://example.org/file'}]}]
"""
return self.call(self.GET_SERVERS, [gid])
def tell_active(self, keys=None):
"""
aria2.tellActive([secret][, keys])
This method returns a list of active downloads. The response is an array of the same structs as returned
by the aria2.tellStatus() method. For the keys parameter, please refer to the aria2.tellStatus() method.
"""
return self.call(self.TELL_ACTIVE, [keys])
def tell_waiting(self, offset, num, keys=None):
"""
aria2.tellWaiting([secret], offset, num[, keys])
This method returns a list of waiting downloads, including paused ones. offset is an integer and specifies
the offset from the download waiting at the front. num is an integer and specifies the max. number of
downloads to be returned. For the keys parameter, please refer to the aria2.tellStatus() method.
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. aria2.tellWaiting(0,
1) returns ["A"]. aria2.tellWaiting(1, 2) returns ["B", "C"]. aria2.tellWaiting(-1, 2) returns ["C", "B"].
The response is an array of the same structs as returned by aria2.tellStatus() method.
"""
return self.call(self.TELL_WAITING, [offset, num, keys])
def tell_stopped(self, offset, num, keys=None):
"""
aria2.tellStopped([secret], offset, num[, keys])
This method returns a list of stopped downloads. offset is an integer and specifies the offset from the
least recently stopped download. num is an integer and specifies the max. number of downloads to be
returned. For the keys parameter, please refer to the aria2.tellStatus() method.
offset and num have the same semantics as described in the aria2.tellWaiting() method.
The response is an array of the same structs as returned by the aria2.tellStatus() method.
"""
return self.call(self.TELL_STOPPED, [offset, num, keys])
def change_position(self, gid, pos, how):
"""
aria2.changePosition([secret], gid, pos, how)
This method changes the position of the download denoted by gid in the queue. pos is an integer. how is
a string. 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. The response is an integer denoting the resulting position.
For example, if GID#2089b05ecca3d829 is currently in position 3, aria2.changePosition('2089b05ecca3d829', -1,
'POS_CUR') will change its position to 2. Additionally aria2.changePosition('2089b05ecca3d829', 0,
'POS_SET') will change its position to 0 (the beginning of the queue).
The following examples move the download GID#2089b05ecca3d829 to the front of the queue.
JSON-RPC Example
>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps({'jsonrpc':'2.0', 'id':'qwer',
... 'method':'aria2.changePosition',
... 'params':['2089b05ecca3d829', 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}
XML-RPC Example
>>> import xmlrpclib
>>> s = xmlrpclib.ServerProxy('http://localhost:6800/rpc')
>>> s.aria2.changePosition('2089b05ecca3d829', 0, 'POS_SET')
0
"""
return self.call(self.CHANGE_POSITION, [gid, pos, how])
def change_uri(self, gid, file_index, del_uris, add_uris, position=None):
"""
aria2.changeUri([secret], gid, fileIndex, delUris, addUris[, position])
This method removes the URIs in delUris from and appends the URIs in addUris to download denoted by gid.
delUris and addUris are lists of strings. A download can contain multiple files and URIs are attached to
each file. fileIndex is used to select which file to remove/attach given URIs. fileIndex is 1-based.
position is 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. When removing an URI, if the same URIs exist in download, only one of them is removed for
each URI in delUris. 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 delUris. This method
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.
The following examples add the URI http://example.org/file to the file whose index is 1 and belongs to the
download GID#2089b05ecca3d829.
JSON-RPC Example
>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps({'jsonrpc':'2.0', 'id':'qwer',
... 'method':'aria2.changeUri',
... 'params':['2089b05ecca3d829', 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]}
XML-RPC Example
>>> import xmlrpclib
>>> s = xmlrpclib.ServerProxy('http://localhost:6800/rpc')
>>> s.aria2.changeUri('2089b05ecca3d829', 1, [], ['http://example.org/file'])
[0, 1]
"""
return self.call(self.CHANGE_URI, [gid, file_index, del_uris, add_uris, position])
def get_option(self, gid):
"""
aria2.getOption([secret], gid)
This method returns options of the download denoted by gid. The response is 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.
The following examples get options of the download GID#2089b05ecca3d829.
JSON-RPC Example
>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps({'jsonrpc':'2.0', 'id':'qwer',
... 'method':'aria2.getOption',
... 'params':['2089b05ecca3d829']})
>>> 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',
...
XML-RPC Example
>>> import xmlrpclib
>>> from pprint import pprint
>>> s = xmlrpclib.ServerProxy('http://localhost:6800/rpc')
>>> r = s.aria2.getOption('2089b05ecca3d829')
>>> pprint(r)
{'allow-overwrite': 'false',
'allow-piece-length-change': 'false',
'always-resume': 'true',
'async-dns': 'true',
....
"""
return self.call(self.GET_OPTION, [gid])
def change_option(self, gid, options):
"""
aria2.changeOption([secret], gid, options)
This method changes options of the download denoted by gid (string) dynamically. options is a struct. 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
This method returns OK for success.
The following examples set the max-download-limit option to 20K for the download GID#2089b05ecca3d829.
JSON-RPC Example
>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps({'jsonrpc':'2.0', 'id':'qwer',
... 'method':'aria2.changeOption',
... 'params':['2089b05ecca3d829',
... {'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'}
XML-RPC Example
>>> import xmlrpclib
>>> s = xmlrpclib.ServerProxy('http://localhost:6800/rpc')
>>> s.aria2.changeOption('2089b05ecca3d829', {'max-download-limit':'20K'})
'OK'
"""
return self.call(self.CHANGE_OPTION, [gid, options])
def get_global_option(self):
"""
aria2.getGlobalOption([secret])
This method returns the global options. The response is a struct. Its keys are the names of options.
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. Because global options are used as a
template for the options of newly added downloads, the response contains keys returned by the
aria2.getOption() method.
"""
return self.call(self.GET_GLOBAL_OPTION)
def change_global_option(self, options):
"""
aria2.changeGlobalOption([secret], options)
This method changes global options dynamically. options is a struct. 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. This method
returns OK for success.
"""
return self.call(self.CHANGE_GLOBAL_OPTION, [options])
def get_global_stat(self):
"""
aria2.getGlobalStat([secret])
This method returns global statistics such as the overall download and upload speeds. The response is a
struct and 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 option.
numStoppedTotal
The number of stopped downloads in the current session and not capped by the
--max-download-result option.
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'}}
XML-RPC Example
>>> import xmlrpclib
>>> from pprint import pprint
>>> s = xmlrpclib.ServerProxy('http://localhost:6800/rpc')
>>> r = s.aria2.getGlobalStat()
>>> pprint(r)
{'downloadSpeed': '23136',
'numActive': '2',
'numStopped': '0',
'numWaiting': '0',
'uploadSpeed': '0'}
"""
return self.call(self.GET_GLOBAL_STAT)
def purge_download_result(self):
"""
aria2.purgeDownloadResult([secret])
This method purges completed/error/removed downloads to free memory. This method returns OK.
"""
return self.call(self.PURGE_DOWNLOAD_RESULT)
def remove_download_result(self, gid):
"""
aria2.removeDownloadResult([secret], gid)
This method removes a completed/error/removed download denoted by gid from memory. This method returns OK for
success.
The following examples remove the download result of the download GID#2089b05ecca3d829.
JSON-RPC Example
>>> import urllib2, json
>>> from pprint import pprint
>>> jsonreq = json.dumps({'jsonrpc':'2.0', 'id':'qwer',
... 'method':'aria2.removeDownloadResult',
... 'params':['2089b05ecca3d829']})
>>> 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'}
XML-RPC Example
>>> import xmlrpclib
>>> s = xmlrpclib.ServerProxy('http://localhost:6800/rpc')
>>> s.aria2.removeDownloadResult('2089b05ecca3d829')
'OK'
"""
return self.call(self.REMOVE_DOWNLOAD_RESULT, [gid])
def get_version(self):
"""
aria2.getVersion([secret])
This method returns the version of aria2 and the list of enabled features. The response is a struct and
contains following keys.
version
Version number of aria2 as a string.
enabledFeatures
List of enabled features. Each feature is given as a string.
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'}}
XML-RPC Example
>>> import xmlrpclib
>>> from pprint import pprint
>>> s = xmlrpclib.ServerProxy('http://localhost:6800/rpc')
>>> r = s.aria2.getVersion()
>>> pprint(r)
{'enabledFeatures': ['Async DNS',
'BitTorrent',
'Firefox3 Cookie',
'GZip',
'HTTPS',
'Message Digest',
'Metalink',
'XML-RPC'],
'version': '1.11.0'}
"""
return self.call(self.GET_VERSION)
def get_session_info(self):
"""
aria2.getSessionInfo([secret])
This method returns session information. The response is a struct and contains following key.
sessionId
Session ID, which is generated each time when aria2 is invoked.
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'}}
XML-RPC Example
>>> import xmlrpclib
>>> s = xmlrpclib.ServerProxy('http://localhost:6800/rpc')
>>> s.aria2.getSessionInfo()
{'sessionId': 'cd6a3bc6a1de28eb5bfa181e5f6b916d44af31a9'}
"""
return self.call(self.GET_SESSION_INFO)
def shutdown(self):
"""
aria2.shutdown([secret])
This method shuts down aria2. This method returns OK.
"""
return self.call(self.SHUTDOWN)
def force_shutdown(self):
"""
aria2.forceShutdown([secret])
This method shuts down aria2(). This method behaves like :func:'aria2.shutdown` without performing any
actions which take time, such as contacting BitTorrent trackers to unregister downloads first. This method
returns OK.
"""
return self.call(self.FORCE_SHUTDOWN)
def save_session(self):
"""
aria2.saveSession([secret])
This method saves the current session to a file specified by the --save-session option. This method returns
OK if it succeeds.
"""
return self.call(self.SAVE_SESSION)
# system
def multicall(self, methods):
"""
system.multicall(methods)
This methods encapsulates multiple method calls in a single request. methods is 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. This method 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.
In the following examples, we add 2 downloads. The first one is http://example.org/file and the second one is
file.torrent.
JSON-RPC Example
>>> 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'2089b05ecca3d829'], [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'2089b05ecca3d829'},
{u'id': u'asdf', u'jsonrpc': u'2.0', u'result': u'd2703803b52216d1'}]
XML-RPC Example
>>> import xmlrpclib
>>> s = xmlrpclib.ServerProxy('http://localhost:6800/rpc')
>>> mc = xmlrpclib.MultiCall(s)
>>> mc.aria2.addUri(['http://example.org/file'])
>>> mc.aria2.addTorrent(xmlrpclib.Binary(open('file.torrent', mode='rb').read()))
>>> r = mc()
>>> tuple(r)
('2089b05ecca3d829', 'd2703803b52216d1')
"""
return self.call(self.MULTICALL, [methods])
def list_methods(self):
"""
system.listMethods()
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.
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',
...
XML-RPC Example
>>> import xmlrpclib
>>> s = xmlrpclib.ServerProxy('http://localhost:6800/rpc')
>>> s.system.listMethods()
['aria2.addUri', 'aria2.addTorrent', ...
"""
return self.call(self.LIST_METHODS)
def list_notifications(self):
"""
system.listNotifications()
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.
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',
...
XML-RPC Example
>>> import xmlrpclib
>>> s = xmlrpclib.ServerProxy('http://localhost:6800/rpc')
>>> s.system.listNotifications()
['aria2.onDownloadStart', 'aria2.onDownloadPause', ...
"""
return self.call(self.LIST_NOTIFICATIONS)
PK ! S? ? aria2p/downloads.py"""
This module defines the BitTorrent, File and Download classes, which respectively hold structured information about
torrent files, files and downloads in aria2c.
"""
from datetime import datetime, timedelta
from pathlib import Path
from .client import ClientException
from .utils import bool_or_value, human_readable_bytes, human_readable_timedelta
class BitTorrent:
"""Information retrieved from a .torrent file."""
def __init__(self, struct):
"""
Initialization method.
Args:
struct (dict): a dictionary Python object returned by the JSON-RPC client.
"""
self._struct = struct
def __str__(self):
return self.info["name"]
@property
def announce_list(self):
"""
List of lists of announce URIs.
If the torrent contains announce and no announce-list, announce is converted to the announce-list format.
"""
return self._struct.get("announceList")
@property
def comment(self):
"""
The comment of the torrent.
comment.utf-8 is used if available.
"""
return self._struct.get("comment")
@property
def creation_date(self):
"""
The creation time of the torrent.
The value is an integer since the epoch, measured in seconds.
"""
return datetime.fromtimestamp(self._struct.get("creationDate"))
@property
def mode(self):
"""
File mode of the torrent.
The value is either single or multi.
"""
return self._struct.get("mode")
@property
def info(self):
"""
Struct which contains data from Info dictionary.
It contains following keys:
name name in info dictionary. name.utf-8 is used if available.
"""
return self._struct.get("info")
class File:
"""Information about a download's file."""
def __init__(self, struct):
"""
Initialization method.
Args:
struct (dict): a dictionary Python object returned by the JSON-RPC client.
"""
self._struct = struct
def __str__(self):
return str(self.path)
def __eq__(self, other):
return self.path == other.path
@property
def index(self):
"""Index of the file, starting at 1, in the same order as files appear in the multi-file torrent."""
return int(self._struct.get("index"))
@property
def path(self):
"""File path."""
return Path(self._struct.get("path"))
@property
def length(self):
"""File size in bytes."""
return int(self._struct.get("length"))
def length_string(self, human_readable=True):
if human_readable:
return human_readable_bytes(self.length, delim=" ")
return str(self.length) + " B"
@property
def completed_length(self):
"""
Completed length of this file in bytes.
Please note that it is possible that sum of completedLength is less than the completedLength returned by the
aria2.tellStatus() method. This is because completedLength in aria2.getFiles() only includes completed
pieces. On the other hand, completedLength in aria2.tellStatus() also includes partially completed pieces.
"""
return int(self._struct.get("completedLength"))
def completed_length_string(self, human_readable=True):
if human_readable:
return human_readable_bytes(self.completed_length, delim=" ")
return str(self.completed_length) + " B"
@property
def selected(self):
"""
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.
"""
return bool_or_value(self._struct.get("selected"))
@property
def uris(self):
"""
Return a list of URIs for this file.
The element type is the same struct used in the aria2.getUris() method.
"""
return self._struct.get("uris")
class Download:
"""Class containing all information about a download, as retrieved with the client."""
def __init__(self, api, struct):
"""
Initialization method.
Args:
api (:class:`aria2p.API`): the reference to an :class:`aria2p.API` instance.
struct (dict): a dictionary Python object returned by the JSON-RPC client.
"""
self.api = api
self._struct = struct
self._files = []
self._bittorrent = None
self._name = ""
self._options = None
self._followed_by = None
self._following = None
self._belongs_to = None
def __str__(self):
return self.name
def __eq__(self, other):
return self.gid == other.gid
def update(self):
"""Method to update the internal values of the download with more recent values."""
self._struct = self.api.client.tell_status(self.gid)
self._files = []
self._name = None
self._bittorrent = None
self._followed_by = []
self._following = None
self._belongs_to = None
@property
def name(self):
"""
The name of the download.
Name is the name of the file if single-file, first file's directory name if multi-file.
"""
if not self._name:
self._name = str(self.files[0].path).replace(str(self.dir), "").lstrip("/").split("/")[0]
return self._name
@property
def options(self):
"""
Options specific to this download.
The returned object is an instance of :class:`aria2p.Options`.
"""
if not self._options:
self.update_options()
return self._options
@options.setter
def options(self, value):
self._options = value
def update_options(self):
self._options = self.api.get_options(downloads=[self])[0]
@property
def gid(self):
"""GID of the download."""
return self._struct.get("gid")
@property
def status(self):
"""Status of the download: active, waiting, paused, error, complete or removed."""
return self._struct.get("status")
@property
def is_active(self):
return self.status == "active"
@property
def is_waiting(self):
return self.status == "waiting"
@property
def is_paused(self):
return self.status == "paused"
@property
def has_failed(self):
return self.status == "error"
@property
def is_complete(self):
return self.status == "complete"
@property
def is_removed(self):
return self.status == "removed"
@property
def total_length(self):
"""Total length of the download in bytes."""
return int(self._struct.get("totalLength"))
def total_length_string(self, human_readable=True):
if human_readable:
return human_readable_bytes(self.total_length, delim=" ")
return str(self.total_length) + " B"
@property
def completed_length(self):
"""Completed length of the download in bytes."""
return int(self._struct.get("completedLength"))
def completed_length_string(self, human_readable=True):
if human_readable:
return human_readable_bytes(self.completed_length, delim=" ")
return str(self.completed_length) + " B"
@property
def upload_length(self):
"""Uploaded length of the download in bytes."""
return int(self._struct.get("uploadLength"))
def upload_length_string(self, human_readable=True):
if human_readable:
return human_readable_bytes(self.upload_length, delim=" ")
return str(self.upload_length) + " B"
@property
def bitfield(self):
"""
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.
"""
return self._struct.get("bitfield")
@property
def download_speed(self):
"""Download speed of this download measured in bytes/sec."""
return int(self._struct.get("downloadSpeed"))
def download_speed_string(self, human_readable=True):
if human_readable:
return human_readable_bytes(self.download_speed, delim=" ", postfix="/s")
return str(self.download_speed) + " B/s"
@property
def upload_speed(self):
"""Upload speed of this download measured in bytes/sec."""
return int(self._struct.get("uploadSpeed"))
def upload_speed_string(self, human_readable=True):
if human_readable:
return human_readable_bytes(self.upload_speed, delim=" ", postfix="/s")
return str(self.upload_speed) + " B/s"
@property
def info_hash(self):
"""
InfoHash.
BitTorrent only.
"""
return self._struct.get("infoHash")
@property
def num_seeders(self):
"""
The number of seeders aria2 has connected to.
BitTorrent only.
"""
return int(self._struct.get("numSeeders"))
@property
def seeder(self):
"""
True if the local endpoint is a seeder, otherwise false.
BitTorrent only.
"""
return bool_or_value(self._struct.get("seeder"))
@property
def piece_length(self):
"""Piece length in bytes."""
return int(self._struct.get("pieceLength"))
def piece_length_string(self, human_readable=True):
if human_readable:
return human_readable_bytes(self.piece_length, delim=" ")
return str(self.piece_length) + " B"
@property
def num_pieces(self):
"""The number of pieces."""
return int(self._struct.get("numPieces"))
@property
def connections(self):
"""The number of peers/servers aria2 has connected to."""
return int(self._struct.get("connections"))
@property
def error_code(self):
"""
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.
"""
return self._struct.get("errorCode")
@property
def error_message(self):
"""The (hopefully) human readable error message associated to errorCode."""
return self._struct.get("errorMessage")
@property
def followed_by_ids(self):
"""
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.
"""
return self._struct.get("followedBy", [])
@property
def followed_by(self):
"""
List of downloads generated as the result of this download.
Returns a list of instances of :class:`aria2p.Download`.
"""
if self._followed_by is None:
result = []
for gid in self.followed_by_ids:
try:
result.append(self.api.get_download(gid))
except ClientException:
pass
self._followed_by = result
return self._followed_by
@property
def following_id(self):
"""
The reverse link for followedBy.
A download included in followedBy has this object's GID in its following value.
"""
return self._struct.get("following")
@property
def following(self):
"""
The download this download is following.
Returns an instance of :class:`aria2p.Download`.
"""
if not self._following:
try:
self._following = self.api.get_download(self.following_id)
except ClientException:
return None
return self._following
@property
def belongs_to_id(self):
"""
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.
"""
return self._struct.get("belongsTo")
@property
def belongs_to(self):
"""
Parent download.
Returns an instance of :class:`aria2p.Download`.
"""
if not self._belongs_to:
try:
self._belongs_to = self.api.get_download(self.belongs_to_id)
except ClientException:
return None
return self._belongs_to
@property
def dir(self):
"""Directory to save files."""
return Path(self._struct.get("dir"))
@property
def files(self):
"""
Return the list of files.
The elements of this list are the same structs used in aria2.getFiles() method.
"""
if not self._files:
self._files = [File(s) for s in self._struct.get("files")]
return self._files
@property
def bittorrent(self):
"""
Struct which contains information retrieved from the .torrent (file).
BitTorrent only.
"""
if not self._bittorrent:
self._bittorrent = BitTorrent(self._struct.get("bittorrent"))
return self._bittorrent
@property
def verified_length(self):
"""
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.
"""
return int(self._struct.get("verifiedLength", 0))
def verified_length_string(self, human_readable=True):
if human_readable:
return human_readable_bytes(self.verified_length, delim=" ")
return str(self.verified_length) + " B"
@property
def verify_integrity_pending(self):
"""
True if this download is waiting for the hash check in a queue.
This key exists only when this download is in the queue.
"""
return bool_or_value(self._struct.get("verifyIntegrityPending"))
@property
def progress(self):
"""Return the progress of the download as float."""
try:
return self.completed_length / self.total_length * 100
except ZeroDivisionError:
return 0.0
def progress_string(self, digits=2):
return f"{self.progress:.{digits}f}%"
@property
def eta(self):
try:
return timedelta(seconds=int((self.total_length - self.completed_length) / self.download_speed))
except ZeroDivisionError:
return float("Inf")
def eta_string(self):
eta = self.eta
if eta == float("Inf"):
return "-"
return human_readable_timedelta(eta)
def move(self, pos):
return self.api.move(self, pos)
def move_to(self, pos):
return self.api.move_to(self, pos)
def move_up(self, pos=1):
return self.api.move_up(self, -pos)
def move_down(self, pos=1):
return self.api.move_down(self, pos)
def move_to_top(self):
return self.api.move_to_top(self)
def move_to_bottom(self):
return self.api.move_to_bottom(self)
def remove(self):
result = self.api.remove([self])[0]
if not result:
raise result
return result
def pause(self):
result = self.api.pause([self])[0]
if not result:
raise result
return result
def resume(self):
result = self.api.resume([self])[0]
if not result:
raise result
return result
PK ! aria2p/options.py"""
This module defines the Options class, which holds information retrieved with the ``get_option`` or
``get_global_option`` methods of the client.
"""
from copy import deepcopy
from .utils import bool_or_value, bool_to_str
class Options:
"""
This class holds information retrieved with the ``get_option`` or ``get_global_option`` methods of the client.
Instances are given a reference to an :class:`aria2p.API` instance to be able to change their values both locally
and remotely, by using the API client and calling remote methods to change options.
The options are available with the same names, using underscores instead of dashes, except for "continue"
(which is a Python reserved keyword) which is here called "continue_downloads". For example,
"max-concurrent-downloads" is used like ``options.max_concurrent_downloads = 5``.
"""
def __init__(self, api, struct, download=None):
"""
Initialization method.
Args:
api (:class:`aria2p.API`): the reference to an :class:`api.API` instance.
struct (dict): a dictionary Python object returned by the JSON-RPC client.
download (:class:`aria2p.Download`): an optional ``Download`` object
to inform about the owner, or None to tell they are global options.
"""
self.api = api
self.download = download
self._struct = struct
@property
def are_global(self):
return self.download is None
def get_struct(self):
return deepcopy(self._struct)
def get(self, item):
return self._struct.get(item)
def set(self, key, value):
if not isinstance(value, str):
value = str(value)
if self.download:
success = self.api.set_options({key: value}, [self.download])[0]
else:
success = self.api.set_global_options({key: value})
if success:
self._struct[key] = value
return success
# Basic Options
@property
def dir(self):
"""
The directory to store the downloaded file.
Returns:
str
"""
return self.get("dir")
@dir.setter
def dir(self, value):
self.set("dir", value)
@property
def input_file(self):
"""
Downloads the URIs listed in FILE.
You can specify multiple sources for a single entity by putting multiple URIs on a single line separated by
the TAB character. Additionally, options can be specified after each URI line. Option lines must start with
one or more white space characters (SPACE or TAB) and must only contain one option per line. Input files can
use gzip compression. When FILE is specified as -, aria2 will read the input from stdin. See the Input File
subsection for details. See also the --deferred-input option. See also the --save-session option.
Returns:
str
"""
return self.get("input-file")
@input_file.setter
def input_file(self, value):
self.set("input-file", value)
@property
def log(self):
"""
The file name of the log file.
If - is specified, log is written to stdout. If empty string("") is
specified, or this option is omitted, no log is written to disk at all.
Returns:
str
"""
return self.get("log")
@log.setter
def log(self, value):
self.set("log", value)
@property
def max_concurrent_downloads(self):
"""
Set the maximum number of parallel downloads for every queue item.
See also the --split option. Default: 5.
Returns:
int
"""
return int(self.get("max-concurrent-downloads"))
@max_concurrent_downloads.setter
def max_concurrent_downloads(self, value):
self.set("max-concurrent-downloads", value)
@property
def check_integrity(self):
"""
Check file integrity by validating piece hashes or a hash of entire file.
This option has effect only in BitTorrent, Metalink downloads with checksums or HTTP(S)/FTP downloads with
--checksum option. If piece hashes are provided, this option can detect damaged portions of a file and
re-download them. If a hash of entire file is provided, hash check is only done when file has been already
downloaded. This is determined by file length. If hash check fails, file is re-downloaded from scratch. If both
piece hashes and a hash of entire file are provided, only piece hashes are used. Default: false.
Returns:
bool
"""
return bool_or_value(self.get("check-integrity"))
@check_integrity.setter
def check_integrity(self, value):
self.set("check-integrity", bool_to_str(value))
@property
def continue_downloads(self):
"""
Continue downloading a partially downloaded file.
Use this option to resume a download started by a web browser or another program which downloads files
sequentially from the beginning. Currently this option is only applicable to HTTP(S)/FTP downloads.
Returns:
bool
"""
return bool_or_value(self.get("continue"))
@continue_downloads.setter
def continue_downloads(self, value):
self.set("continue", bool_to_str(value))
# FIXME: might not be an option (only command-line argument)
@property
def help(self):
"""
The help messages are classified with tags.
A tag starts with #. For example, type --help=#http to get the usage for the options tagged with #http. If
non-tag word is given, print the usage for the options whose name includes that word. Available Values:
#basic, #advanced, #http, #https, #ftp, #metalink, #bittorrent, #cookie, #hook, #file, #rpc, #checksum,
#experimental, #deprecated, #help, #all Default: #basic
"""
return self.get("help")
@help.setter
def help(self, value):
self.set("help", value)
# HTTP/FTP/SFTP Options
@property
def all_proxy(self):
"""
Use a proxy server for all protocols.
To override a previously defined proxy, use "". You also can override this setting and specify a proxy server
for a particular protocol using --http-proxy, --https-proxy and --ftp-proxy options. This affects all
downloads. The format of PROXY is [http://][ USER:PASSWORD@]HOST[:PORT]. See also ENVIRONMENT section.
NOTE:
If user and password are embedded in proxy URI and they are also specified by --{http,https,ftp,
all}-proxy-{user,passwd} options, those specified later override prior options. For example,
if you specified http-proxy-user=myname, http-proxy-passwd=mypass in aria2.conf and you specified
--http-proxy="http://proxy" on the command-line, then you'd get HTTP proxy http://proxy with user myname
and password mypass.
Another example: if you specified on the command-line --http-proxy="http://user:pass@proxy"
--http-proxy-user="myname" --http-proxy-passwd="mypass", then you'd get HTTP proxy http://proxy with user
myname and password mypass.
One more example: if you specified in command-line --http-proxy-user="myname"
--http-proxy-passwd="mypass" --http-proxy="http://user:pass@proxy", then you'd get HTTP proxy
http://proxy with user user and password pass.
Returns:
str
"""
return self.get("all-proxy")
@all_proxy.setter
def all_proxy(self, value):
self.set("all-proxy", value)
@property
def all_proxy_passwd(self):
"""
Set password for --all-proxy option.
Returns:
str
"""
return self.get("all-proxy-passwd")
@all_proxy_passwd.setter
def all_proxy_passwd(self, value):
self.set("all-proxy-passwd", value)
@property
def all_proxy_user(self):
"""
Set user for --all-proxy option.
Returns:
str
"""
return self.get("all-proxy-user")
@all_proxy_user.setter
def all_proxy_user(self, value):
self.set("all-proxy-user", value)
@property
def checksum(self):
"""
Set checksum (=).
TYPE is hash type. The supported hash type is listed in Hash Algorithms in aria2c -v. DIGEST is hex digest.
For example, setting sha-1 digest looks like this: sha-1=0192ba11326fe2298c8cb4de616f4d4140213838 This option
applies only to HTTP(S)/FTP downloads.
Returns:
str
"""
return self.get("checksum")
@checksum.setter
def checksum(self, value):
self.set("checksum", value)
@property
def connect_timeout(self):
"""
Set the connect timeout in seconds to establish connection to HTTP/FTP/proxy server.
After the connection is established, this option makes no effect and --timeout option is used instead.
Default: 60.
Returns:
int
"""
return int(self.get("connect-timeout"))
@connect_timeout.setter
def connect_timeout(self, value):
self.set("connect-timeout", value)
@property
def dry_run(self):
"""
If true is given, aria2 just checks whether the remote file is available and doesn't download data.
This option has effect on HTTP/FTP download. BitTorrent downloads are canceled if true is specified. Default:
false.
Returns:
bool
"""
return bool_or_value(self.get("dry-run"))
@dry_run.setter
def dry_run(self, value):
self.set("dry-run", bool_to_str(value))
@property
def lowest_speed_limit(self):
"""
Close connection if download speed is lower than or equal to this value(bytes per sec).
0 means aria2 does not have a lowest speed limit. You can append K or M (1K = 1024, 1M = 1024K). This option
does not affect BitTorrent downloads. Default: 0.
Returns:
int
"""
return int(self.get("lowest-speed-limit"))
@lowest_speed_limit.setter
def lowest_speed_limit(self, value):
self.set("lowest-speed-limit", value)
@property
def max_connection_per_server(self):
"""
The maximum number of connections to one server for each download.
Default: 1.
Returns:
int
"""
return int(self.get("max-connection-per-server"))
@max_connection_per_server.setter
def max_connection_per_server(self, value):
self.set("max-connection-per-server", value)
@property
def max_file_not_found(self):
"""
If aria2 receives "file not found" status from the remote HTTP/FTP servers NUM times without getting a single
byte, then force the download to fail.
Specify 0 to disable this option. This options is effective only when using HTTP/FTP servers. The number of
retry attempt is counted toward --max-tries, so it should be configured too.
Default: 0.
Returns:
int
"""
return int(self.get("max-file-not-found"))
@max_file_not_found.setter
def max_file_not_found(self, value):
self.set("max-file-not-found", value)
@property
def max_tries(self):
"""
Set number of tries.
0 means unlimited. See also --retry-wait. Default: 5.
Returns:
int
"""
return int(self.get("max-tries"))
@max_tries.setter
def max_tries(self, value):
self.set("max-tries", value)
@property
def min_split_size(self):
"""
aria2 does not split less than 2*SIZE byte range.
For example, let's consider downloading 20MiB file. If SIZE is 10M, aria2 can split file into 2 range [
0-10MiB) and [10MiB-20MiB) and download it using 2 sources(if --split >= 2, of course). If SIZE is 15M,
since 2*15M > 20MiB, aria2 does not split file and download it using 1 source. You can append K or M (1K =
1024, 1M = 1024K). Possible Values: 1M -1024M Default: 20M
Returns:
int
"""
return int(self.get("min-split-size"))
@min_split_size.setter
def min_split_size(self, value):
self.set("min-split-size", value)
@property
def netrc_path(self):
"""
Specify the path to the netrc file.
Default: $(HOME)/.netrc.
NOTE:
Permission of the .netrc file must be 600. Otherwise, the file will be ignored.
Returns:
str
"""
return self.get("netrc-path")
@netrc_path.setter
def netrc_path(self, value):
self.set("netrc-path", value)
@property
def no_netrc(self):
"""
Disable netrc support.
netrc support is enabled by default.
NOTE:
netrc file is only read at the startup if --no-netrc is false. So if --no-netrc is true at the startup,
no netrc is available throughout the session. You cannot get netrc enabled even if you send
--no-netrc=false using aria2.changeGlobalOption().
Returns:
bool
"""
return bool_or_value(self.get("no-netrc"))
@no_netrc.setter
def no_netrc(self, value):
self.set("no-netrc", bool_to_str(value))
@property
def no_proxy(self):
"""
Specify a comma separated list of host names, domains and network addresses with or without a subnet mask
where no proxy should be used.
NOTE:
For network addresses with a subnet mask, both IPv4 and IPv6 addresses work. The current implementation
does not resolve the host name in an URI to compare network addresses specified in --no-proxy. So it is
only effective if URI has numeric IP addresses.
Returns:
str
"""
return self.get("no-proxy")
@no_proxy.setter
def no_proxy(self, value):
self.set("no-proxy", value)
@property
def out(self):
"""
The file name of the downloaded file.
It is always relative to the directory given in --dir option. When the --force-sequential option is used,
this option is ignored.
NOTE:
You cannot specify a file name for Metalink or BitTorrent downloads. The file name specified here is only
used when the URIs fed to aria2 are given on the command line directly, but not when using --input-file,
--force-sequential option.
Example:
$ aria2c -o myfile.zip "http://mirror1/file.zip" "http://mirror2/file.zip"
Returns:
str
"""
return self.get("out")
@out.setter
def out(self, value):
self.set("out", value)
@property
def proxy_method(self):
"""
Set the method to use in proxy request.
METHOD is either get or tunnel. HTTPS downloads always use tunnel regardless of this option. Default: get
Returns:
str
"""
return self.get("proxy-method")
@proxy_method.setter
def proxy_method(self, value):
self.set("proxy-method", value)
@property
def remote_time(self):
"""
Retrieve timestamp of the remote file from the remote HTTP/FTP server and if it is available, apply it to the
local file.
Default: false.
Returns:
bool
"""
return bool_or_value(self.get("remote-time"))
@remote_time.setter
def remote_time(self, value):
self.set("remote-time", bool_to_str(value))
@property
def reuse_uri(self):
"""
Reuse already used URIs if no unused URIs are left.
Default: true.
Returns:
bool
"""
return bool_or_value(self.get("reuse-uri"))
@reuse_uri.setter
def reuse_uri(self, value):
self.set("reuse-uri", bool_to_str(value))
@property
def retry_wait(self):
"""
Set the seconds to wait between retries.
When SEC > 0, aria2 will retry downloads when the HTTP server returns a 503 response. Default: 0.
Returns:
int
"""
return int(self.get("retry-wait"))
@retry_wait.setter
def retry_wait(self, value):
self.set("retry-wait", value)
@property
def server_stat_of(self):
"""
Specify the file name to which performance profile of the servers is saved.
You can load saved data using --server-stat-if option. See Server Performance Profile subsection below for
file format.
Returns:
str
"""
return self.get("server-stat-of")
@server_stat_of.setter
def server_stat_of(self, value):
self.set("server-stat-of", value)
@property
def server_stat_if(self):
"""
Specify the file name to load performance profile of the servers.
The loaded data will be used in some URI selector such as feedback. See also --uri-selector option. See
Server Performance Profile subsection below for file format.
Returns:
str
"""
return self.get("server-stat-if")
@server_stat_if.setter
def server_stat_if(self, value):
self.set("server-stat-if", value)
@property
def server_stat_timeout(self):
"""
Specifies timeout in seconds to invalidate performance profile of the servers since the last contact to
them.
Default: 86400 (24hours).
Returns:
int
"""
return int(self.get("server-stat-timeout"))
@server_stat_timeout.setter
def server_stat_timeout(self, value):
self.set("server-stat-timeout", value)
@property
def split(self):
"""
Download a file using N connections.
If more than N URIs are given, first N URIs are used and remaining URIs are used for backup. If less than N
URIs are given, those URIs are used more than once so that N connections total are made simultaneously. The
number of connections to the same host is restricted by the --max-connection-per-server option. See also the
--min-split-size option. Default: 5
NOTE:
Some Metalinks regulate the number of servers to connect. aria2 strictly respects them. This means that
if Metalink defines the maxconnections attribute lower than N, then aria2 uses the value of this lower
value instead of N.
Returns:
int
"""
return int(self.get("split"))
@split.setter
def split(self, value):
self.set("split", value)
@property
def stream_piece_selector(self):
"""
Specify piece selection algorithm used in HTTP/FTP download.
Piece means fixed length segment which is downloaded in parallel in segmented download. If default is given,
aria2 selects piece so that it reduces the number of establishing connection. This is reasonable default
behavior because establishing connection is an expensive operation. If inorder is given, aria2 selects piece
which has minimum index. Index=0 means first of the file. This will be useful to view movie while downloading
it. --enable-http-pipelining option may be useful to reduce re-connection overhead. Please note that aria2
honors --min-split-size option, so it will be necessary to specify a reasonable value to --min-split-size
option. If random is given, aria2 selects piece randomly. Like inorder, --min-split-size option is honored.
If geom is given, at the beginning aria2 selects piece which has minimum index like inorder,
but it exponentially increasingly keeps space from previously selected piece. This will reduce the number of
establishing connection and at the same time it will download the beginning part of the file first. This will
be useful to view movie while downloading it. Default: default.
Returns:
str
"""
return self.get("stream-piece-selector")
@stream_piece_selector.setter
def stream_piece_selector(self, value):
self.set("stream-piece-selector", value)
@property
def timeout(self):
"""
Set timeout in seconds.
Default: 60.
Returns:
int
"""
return int(self.get("timeout"))
@timeout.setter
def timeout(self, value):
self.set("timeout", value)
@property
def uri_selector(self):
"""
Specify URI selection algorithm.
The possible values are inorder, feedback and adaptive. If inorder is given, URI is tried in the order
appeared in the URI list. If feedback is given, aria2 uses download speed observed in the previous downloads
and choose fastest server in the URI list. This also effectively skips dead mirrors. The observed download
speed is a part of performance profile of servers mentioned in --server-stat-of and --server-stat-if options.
If adaptive is given, selects one of the best mirrors for the first and reserved connections. For
supplementary ones, it returns mirrors which has not been tested yet, and if each of them has already been
tested, returns mirrors which has to be tested again. Otherwise, it doesn't select anymore mirrors. Like
feedback, it uses a performance profile of servers. Default: feedback.
Returns:
str
"""
return self.get("uri-selector")
@uri_selector.setter
def uri_selector(self, value):
self.set("uri-selector", value)
# HTTP Specific Options
@property
def ca_certificate(self):
"""
Use the certificate authorities in FILE to verify the peers.
The certificate file must be in PEM format and can contain multiple CA certificates. Use --check-certificate
option to enable verification.
NOTE:
If you build with OpenSSL or the recent version of GnuTLS which has
gnutls_certificate_set_x509_system_trust() function and the library is properly configured to locate the
system-wide CA certificates store, aria2 will automatically load those certificates at the startup.
NOTE:
WinTLS and AppleTLS do not support this option. Instead you will have to import the certificate into the
OS trust store.
Returns:
str
"""
return self.get("ca-certificate")
@ca_certificate.setter
def ca_certificate(self, value):
self.set("ca-certificate", value)
@property
def certificate(self):
"""
Use the client certificate in FILE.
The certificate must be either in PKCS12 (.p12, .pfx) or in PEM format.
PKCS12 files must contain the certificate, a key and optionally a chain of additional certificates. Only
PKCS12 files with a blank import password can be opened!
When using PEM, you have to specify the private key via --private-key as well.
NOTE:
WinTLS does not support PEM files at the moment. Users have to use PKCS12 files.
NOTE:
AppleTLS users should use the KeyChain Access utility to import the client certificate and get the SHA-1
fingerprint from the Information dialog corresponding to that certificate. To start aria2c use
--certificate=. Alternatively PKCS12 files are also supported. PEM files, however, are not supported.
Returns:
str
"""
return self.get("certificate")
@certificate.setter
def certificate(self, value):
self.set("certificate", value)
@property
def check_certificate(self):
"""
Verify the peer using certificates specified in --ca-certificate option.
Default: true.
Returns:
bool
"""
return bool_or_value(self.get("check-certificate"))
@check_certificate.setter
def check_certificate(self, value):
self.set("check-certificate", bool_to_str(value))
@property
def http_accept_gzip(self):
"""
Send Accept: deflate, gzip request header and inflate response if remote server responds with
Content-Encoding: gzip or Content-Encoding: deflate.
Default: false.
NOTE:
Some server responds with Content-Encoding: gzip for files which itself is gzipped file. aria2 inflates
them anyway because of the response header.
Returns:
bool
"""
return bool_or_value(self.get("http-accept-gzip"))
@http_accept_gzip.setter
def http_accept_gzip(self, value):
self.set("http-accept-gzip", bool_to_str(value))
@property
def http_auth_challenge(self):
"""
Send HTTP authorization header only when it is requested by the server.
If false is set, then authorization header is always sent to the server. There is an exception: if user name
and password are embedded in URI, authorization header is always sent to the server regardless of this
option. Default: false.
Returns:
bool
"""
return bool_or_value(self.get("http-auth-challenge"))
@http_auth_challenge.setter
def http_auth_challenge(self, value):
self.set("http-auth-challenge", bool_to_str(value))
@property
def http_no_cache(self):
"""
Send Cache-Control: no-cache and Pragma: no-cache header to avoid cached content.
If false is given, these headers are not sent and you can add Cache-Control header with a directive you like
using --header option. Default: false.
Returns:
bool
"""
return bool_or_value(self.get("http-no-cache"))
@http_no_cache.setter
def http_no_cache(self, value):
self.set("http-no-cache", bool_to_str(value))
@property
def http_user(self):
"""
Set HTTP user. This affects all URIs.
Returns:
str
"""
return self.get("http-user")
@http_user.setter
def http_user(self, value):
self.set("http-user", value)
@property
def http_passwd(self):
"""
Set HTTP password. This affects all URIs.
Returns:
str
"""
return self.get("http-passwd")
@http_passwd.setter
def http_passwd(self, value):
self.set("http-passwd", value)
@property
def http_proxy(self):
"""
Use a proxy server for HTTP.
To override a previously defined proxy, use "". See also the --all-proxy option. This affects all http
downloads. The format of PROXY is [http://][USER:PASSWORD@]HOST[:PORT]
Returns:
str
"""
return self.get("http-proxy")
@http_proxy.setter
def http_proxy(self, value):
self.set("http-proxy", value)
@property
def http_proxy_passwd(self):
"""
Set password for --http-proxy.
Returns:
str
"""
return self.get("http-proxy-passwd")
@http_proxy_passwd.setter
def http_proxy_passwd(self, value):
self.set("http-proxy-passwd", value)
@property
def http_proxy_user(self):
"""
Set user for --http-proxy.
Returns:
str
"""
return self.get("http-proxy-user")
@http_proxy_user.setter
def http_proxy_user(self, value):
self.set("http-proxy-user", value)
@property
def https_proxy(self):
"""
Use a proxy server for HTTPS.
To override a previously defined proxy, use "". See also the --all-proxy option. This affects all https
download. The format of PROXY is [http://][USER:PASSWORD@]HOST[:PORT].
Returns:
str
"""
return self.get("https-proxy")
@https_proxy.setter
def https_proxy(self, value):
self.set("https-proxy", value)
@property
def https_proxy_passwd(self):
"""
Set password for --https-proxy.
Returns:
str
"""
return self.get("https-proxy-passwd")
@https_proxy_passwd.setter
def https_proxy_passwd(self, value):
self.set("https-proxy-passwd", value)
@property
def https_proxy_user(self):
"""
Set user for --https-proxy.
Returns:
str
"""
return self.get("https-proxy-user")
@https_proxy_user.setter
def https_proxy_user(self, value):
self.set("https-proxy-user", value)
@property
def private_key(self):
"""
Use the private key in FILE.
The private key must be decrypted and in PEM format. The behavior when encrypted one is given is undefined.
See also --certificate option.
Returns:
str
"""
return self.get("private-key")
@private_key.setter
def private_key(self, value):
self.set("private-key", value)
@property
def referer(self):
"""
Set an http referrer (Referer).
This affects all http/https downloads. If * is given, the download URI is also used as the referrer. This may
be useful when used together with the --parameterized-uri option.
Returns:
str
"""
return self.get("referer")
@referer.setter
def referer(self, value):
self.set("referer", value)
@property
def enable_http_keep_alive(self):
"""
Enable HTTP/1.1 persistent connection.
Default: true.
Returns:
bool
"""
return bool_or_value(self.get("enable-http-keep-alive"))
@enable_http_keep_alive.setter
def enable_http_keep_alive(self, value):
self.set("enable-http-keep-alive", bool_to_str(value))
@property
def enable_http_pipelining(self):
"""
Enable HTTP/1.1 pipelining.
Default: false.
NOTE:
In performance perspective, there is usually no advantage to enable this option.
Returns:
bool
"""
return bool_or_value(self.get("enable-http-pipelining"))
@enable_http_pipelining.setter
def enable_http_pipelining(self, value):
self.set("enable-http-pipelining", bool_to_str(value))
@property
def header(self):
"""
Append HEADER to HTTP request header.
You can use this option repeatedly to specify more than one header:
$ aria2c --header="X-A: b78" --header="X-B: 9J1" "http://host/file"
Returns:
str
"""
return self.get("header")
@header.setter
def header(self, value):
self.set("header", value)
@property
def load_cookies(self):
"""
Load Cookies from FILE using the Firefox3 format (SQLite3), Chromium/Google Chrome (SQLite3) and the
Mozilla/Firefox(1.x/2.x)/Netscape format.
NOTE:
If aria2 is built without libsqlite3, then it doesn't support Firefox3 and Chromium/Google Chrome cookie
format.
Returns:
str
"""
return self.get("load-cookies")
@load_cookies.setter
def load_cookies(self, value):
self.set("load-cookies", value)
@property
def save_cookies(self):
"""
Save Cookies to FILE in Mozilla/Firefox(1.x/2.x)/ Netscape format.
If FILE already exists, it is overwritten. Session Cookies are also saved and their expiry values are treated
as 0. Possible Values: /path/to/file.
Returns:
str
"""
return self.get("save-cookies")
@save_cookies.setter
def save_cookies(self, value):
self.set("save-cookies", value)
@property
def use_head(self):
"""
Use HEAD method for the first request to the HTTP server.
Default: false.
Returns:
bool
"""
return bool_or_value(self.get("use-head"))
@use_head.setter
def use_head(self, value):
self.set("use-head", bool_to_str(value))
@property
def user_agent(self):
"""
Set user agent for HTTP(S) downloads.
Default: aria2/$VERSION, $VERSION is replaced by package version.
Returns:
str
"""
return self.get("user-agent")
@user_agent.setter
def user_agent(self, value):
self.set("user-agent", value)
# FTP/SFTP Specific Options
@property
def ftp_user(self):
"""
Set FTP user. This affects all URIs.
Default: anonymous.
Returns:
str
"""
return self.get("ftp-user")
@ftp_user.setter
def ftp_user(self, value):
self.set("ftp-user", value)
@property
def ftp_passwd(self):
"""
Set FTP password. This affects all URIs.
If user name is embedded but password is missing in URI, aria2 tries to resolve password using .netrc. If
password is found in .netrc, then use it as password. If not, use the password specified in this option.
Default: ARIA2USER@.
Returns:
str
"""
return self.get("ftp-passwd")
@ftp_passwd.setter
def ftp_passwd(self, value):
self.set("ftp-passwd", value)
@property
def ftp_pasv(self):
"""
Use the passive mode in FTP.
If false is given, the active mode will be used. Default: true.
NOTE:
This option is ignored for SFTP transfer.
Returns:
bool
"""
return bool_or_value(self.get("ftp-pasv"))
@ftp_pasv.setter
def ftp_pasv(self, value):
self.set("ftp-pasv", bool_to_str(value))
@property
def ftp_proxy(self):
"""
Use a proxy server for FTP.
To override a previously defined proxy, use "". See also the --all-proxy option. This affects all ftp
downloads. The format of PROXY is [http://][USER:PASSWORD@]HOST[:PORT]
Returns:
str
"""
return self.get("ftp-proxy")
@ftp_proxy.setter
def ftp_proxy(self, value):
self.set("ftp-proxy", value)
@property
def ftp_proxy_passwd(self):
"""
Set password for --ftp-proxy option.
Returns:
str
"""
return self.get("ftp-proxy-passwd")
@ftp_proxy_passwd.setter
def ftp_proxy_passwd(self, value):
self.set("ftp-proxy-passwd", value)
@property
def ftp_proxy_user(self):
"""
Set user for --ftp-proxy option.
Returns:
str
"""
return self.get("ftp-proxy-user")
@ftp_proxy_user.setter
def ftp_proxy_user(self, value):
self.set("ftp-proxy-user", value)
@property
def ftp_type(self):
"""
Set FTP transfer type.
TYPE is either binary or ascii. Default: binary.
NOTE:
This option is ignored for SFTP transfer.
Returns:
str
"""
return self.get("ftp-type")
@ftp_type.setter
def ftp_type(self, value):
self.set("ftp-type", value)
@property
def ftp_reuse_connection(self):
"""
Reuse connection in FTP.
Default: true.
Returns:
bool
"""
return bool_or_value(self.get("ftp-reuse-connection"))
@ftp_reuse_connection.setter
def ftp_reuse_connection(self, value):
self.set("ftp-reuse-connection", bool_to_str(value))
@property
def ssh_host_key_md(self):
"""
Set checksum for SSH host public key (=).
TYPE is hash type. The supported hash type is sha-1 or md5. DIGEST is hex digest. For example:
sha-1=b030503d4de4539dc7885e6f0f5e256704edf4c3. This option can be used to validate server's public key when
SFTP is used. If this option is not set, which is default, no validation takes place.
Returns:
str
"""
return self.get("ssh-host-key-md")
@ssh_host_key_md.setter
def ssh_host_key_md(self, value):
self.set("ssh-host-key-md", value)
# BitTorrent/Metalink Options
@property
def select_file(self):
"""
Set file to download by specifying its index.
You can find the file index using the --show-files option. Multiple indexes can be specified by using ,,
for example: 3,6. You can also use - to specify a range: 1-5. , and - can be used together: 1-5,8,
9. When used with the -M option, index may vary depending on the query (see --metalink-* options).
NOTE:
In multi file torrent, the adjacent files specified by this option may also be downloaded. This is by
design, not a bug. A single piece may include several files or part of files, and aria2 writes the piece
to the appropriate files.
Returns:
str
"""
return self.get("select-file")
@select_file.setter
def select_file(self, value):
self.set("select-file", value)
@property
def show_files(self):
"""
Print file listing of ".torrent", ".meta4" and ".metalink" file and exit.
In case of ".torrent" file, additional information (infohash, piece length, etc) is also printed.
Returns:
bool
"""
return bool_or_value(self.get("show-files"))
@show_files.setter
def show_files(self, value):
self.set("show-files", bool_to_str(value))
# BitTorrent Specific Options
@property
def bt_detach_seed_only(self):
"""
Exclude seed only downloads when counting concurrent active downloads (See -j option).
This means that if -j3 is given and this option is turned on and 3 downloads are active and one of those
enters seed mode, then it is excluded from active download count (thus it becomes 2), and the next download
waiting in queue gets started. But be aware that seeding item is still recognized as active download in RPC
method. Default: false.
Returns:
bool
"""
return bool_or_value(self.get("bt-detach-seed-only"))
@bt_detach_seed_only.setter
def bt_detach_seed_only(self, value):
self.set("bt-detach-seed-only", bool_to_str(value))
@property
def bt_enable_hook_after_hash_check(self):
"""
Allow hook command invocation after hash check (see -V option) in BitTorrent download.
By default, when hash check succeeds, the command given by --on-bt-download-complete is executed. To disable
this action, give false to this option. Default: true.
Returns:
bool
"""
return bool_or_value(self.get("bt_enable_hook_after_hash_check"))
@bt_enable_hook_after_hash_check.setter
def bt_enable_hook_after_hash_check(self, value):
self.set("bt_enable_hook_after_hash_check", bool_to_str(value))
@property
def bt_enable_lpd(self):
"""
Enable Local Peer Discovery.
If a private flag is set in a torrent, aria2 doesn't use this feature for that download even if true is
given. Default: false.
Returns:
bool
"""
return bool_or_value(self.get("bt-enable-lpd"))
@bt_enable_lpd.setter
def bt_enable_lpd(self, value):
self.set("bt-enable-lpd", bool_to_str(value))
@property
def bt_exclude_tracker(self):
"""
Comma separated list of BitTorrent tracker's announce URI to remove.
You can use special value * which matches all URIs, thus removes all announce URIs. When specifying * in
shell command-line, don't forget to escape or quote it. See also --bt-tracker option.
Returns:
list of str
"""
return self.get("bt-exclude-tracker")
@bt_exclude_tracker.setter
def bt_exclude_tracker(self, value):
self.set("bt-exclude-tracker", value)
@property
def bt_external_ip(self):
"""
Specify the external IP address to use in BitTorrent download and DHT.
It may be sent to BitTorrent tracker. For DHT, this option should be set to report that local node is
downloading a particular torrent. This is critical to use DHT in a private network. Although this function is
named external, it can accept any kind of IP addresses.
Returns:
str
"""
return self.get("bt-external-ip")
@bt_external_ip.setter
def bt_external_ip(self, value):
self.set("bt-external-ip", value)
@property
def bt_force_encryption(self):
"""
Requires BitTorrent message payload encryption with arc4.
This is a shorthand of --bt-require-crypto --bt-min-crypto-level=arc4. This option does not change the option
value of those options. If true is given, deny legacy BitTorrent handshake and only use Obfuscation handshake
and always encrypt message payload. Default: false.
Returns:
bool
"""
return bool_or_value(self.get("bt-force-encryption"))
@bt_force_encryption.setter
def bt_force_encryption(self, value):
self.set("bt-force-encryption", bool_to_str(value))
@property
def bt_hash_check_seed(self):
"""
If true is given, after hash check using --check-integrity option and file is complete, continue to seed
file.
If you want to check file and download it only when it is damaged or incomplete, set this option to false.
This option has effect only on BitTorrent download. Default: true
Returns:
bool
"""
return bool_or_value(self.get("bt-hash-check-seed"))
@bt_hash_check_seed.setter
def bt_hash_check_seed(self, value):
self.set("bt-hash-check-seed", bool_to_str(value))
@property
def bt_lpd_interface(self):
"""
Use given interface for Local Peer Discovery.
If this option is not specified, the default interface is chosen. You can specify interface name and IP
address. Possible Values: interface, IP address.
Returns:
str
"""
return self.get("bt-lpd-interface")
@bt_lpd_interface.setter
def bt_lpd_interface(self, value):
self.set("bt-lpd-interface", value)
@property
def bt_max_open_files(self):
"""
Specify maximum number of files to open in multi-file BitTorrent/Metalink download globally.
Default: 100.
Returns:
int
"""
return int(self.get("bt-max-open-files"))
@bt_max_open_files.setter
def bt_max_open_files(self, value):
self.set("bt-max-open-files", value)
@property
def bt_max_peers(self):
"""
Specify the maximum number of peers per torrent. 0 means unlimited.
See also --bt-request-peer-speed-limit option. Default: 55.
Returns:
int
"""
return int(self.get("bt-max-peers"))
@bt_max_peers.setter
def bt_max_peers(self, value):
self.set("bt-max-peers", value)
@property
def bt_metadata_only(self):
"""
Download meta data only.
The file(s) described in meta data will not be downloaded. This option has effect only when BitTorrent Magnet
URI is used. See also --bt-save-metadata option. Default: false.
Returns:
bool
"""
return bool_or_value(self.get("bt-metadata-only"))
@bt_metadata_only.setter
def bt_metadata_only(self, value):
self.set("bt-metadata-only", bool_to_str(value))
@property
def bt_min_crypto_level(self):
"""
Set minimum level of encryption method (plain/arc4).
If several encryption methods are provided by a peer, aria2 chooses the lowest one which satisfies the given
level. Default: plain.
Returns:
str
"""
return self.get("bt-min-crypto-level")
@bt_min_crypto_level.setter
def bt_min_crypto_level(self, value):
self.set("bt-min-crypto-level", value)
@property
def bt_prioritize_piece(self):
"""
Try to download first and last pieces of each file first (head[=],tail[=]).
This is useful for previewing files. The argument can contain 2 keywords: head and tail. To include both
keywords, they must be separated by comma. These keywords can take one parameter, SIZE. For example,
if head= is specified, pieces in the range of first SIZE bytes of each file get higher priority.
tail= means the range of last SIZE bytes of each file. SIZE can include K or M (1K = 1024, 1M = 1024K).
If SIZE is omitted, SIZE=1M is used.
Returns:
str
"""
return self.get("bt-prioritize-piece")
@bt_prioritize_piece.setter
def bt_prioritize_piece(self, value):
self.set("bt-prioritize-piece", value)
@property
def bt_remove_unselected_file(self):
"""
Removes the unselected files when download is completed in BitTorrent.
To select files, use --select-file option. If it is not used, all files are assumed to be selected. Please
use this option with care because it will actually remove files from your disk. Default: false.
Returns:
bool
"""
return bool_or_value(self.get("bt-remove-unselected-file"))
@bt_remove_unselected_file.setter
def bt_remove_unselected_file(self, value):
self.set("bt-remove-unselected-file", bool_to_str(value))
@property
def bt_require_crypto(self):
"""
If true is given, aria2 doesn't accept and establish connection with legacy BitTorrent handshake
(\19BitTorrent protocol).
Thus aria2 always uses Obfuscation handshake. Default: false.
Returns:
bool
"""
return bool_or_value(self.get("bt-require-crypto"))
@bt_require_crypto.setter
def bt_require_crypto(self, value):
self.set("bt-require-crypto", bool_to_str(value))
@property
def bt_request_peer_speed_limit(self):
"""
If the whole download speed of every torrent is lower than SPEED, aria2 temporarily increases the number
of peers to try for more download speed.
Configuring this option with your preferred download speed can increase your download speed in some cases.
You can append K or M (1K = 1024, 1M = 1024K). Default: 50K.
Returns:
int
"""
return int(self.get("bt-request-peer-speed-limit"))
@bt_request_peer_speed_limit.setter
def bt_request_peer_speed_limit(self, value):
self.set("bt-request-peer-speed-limit", value)
@property
def bt_save_metadata(self):
"""
Save meta data as ".torrent" file.
This option has effect only when BitTorrent Magnet URI is used. The file name is hex encoded info hash with
suffix ".torrent". The directory to be saved is the same directory where download file is saved. If the same
file already exists, meta data is not saved. See also --bt-metadata-only option. Default: false.
Returns:
bool
"""
return bool_or_value(self.get("bt-save-metadata"))
@bt_save_metadata.setter
def bt_save_metadata(self, value):
self.set("bt-save-metadata", bool_to_str(value))
@property
def bt_seed_unverified(self):
"""
Seed previously downloaded files without verifying piece hashes.
Default: false.
Returns:
bool
"""
return bool_or_value(self.get("bt-seed-unverified"))
@bt_seed_unverified.setter
def bt_seed_unverified(self, value):
self.set("bt-seed-unverified", bool_to_str(value))
@property
def bt_stop_timeout(self):
"""
Stop BitTorrent download if download speed is 0 in consecutive SEC seconds.
If 0 is given, this feature is disabled. Default: 0.
Returns:
int
"""
return int(self.get("bt-stop-timeout"))
@bt_stop_timeout.setter
def bt_stop_timeout(self, value):
self.set("bt-stop-timeout", value)
@property
def bt_tracker(self):
"""
Comma separated list of additional BitTorrent tracker's announce URI.
These URIs are not affected by --bt-exclude-tracker option because they are added after URIs in
--bt-exclude-tracker option are removed.
Returns:
list of str
"""
return self.get("bt-tracker")
@bt_tracker.setter
def bt_tracker(self, value):
self.set("bt-tracker", value)
@property
def bt_tracker_connect_timeout(self):
"""
Set the connect timeout in seconds to establish connection to tracker.
After the connection is established, this option makes no effect and --bt-tracker-timeout option is used
instead. Default: 60.
Returns:
int
"""
return int(self.get("bt-tracker-connect-timeout"))
@bt_tracker_connect_timeout.setter
def bt_tracker_connect_timeout(self, value):
self.set("bt-tracker-connect-timeout", value)
@property
def bt_tracker_interval(self):
"""
Set the interval in seconds between tracker requests.
This completely overrides interval value and aria2 just uses this value and ignores the min interval and
interval value in the response of tracker. If 0 is set, aria2 determines interval based on the response of
tracker and the download progress. Default: 0.
Returns:
int
"""
return int(self.get("bt-tracker-interval"))
@bt_tracker_interval.setter
def bt_tracker_interval(self, value):
self.set("bt-tracker-interval", value)
@property
def bt_tracker_timeout(self):
"""
Set timeout in seconds.
Default: 60.
Returns:
int
"""
return int(self.get("bt-tracker-timeout"))
@bt_tracker_timeout.setter
def bt_tracker_timeout(self, value):
self.set("bt-tracker-timeout", value)
@property
def dht_entry_point(self):
"""
Set host and port as an entry point to IPv4 DHT network (:).
Returns:
str
"""
return self.get("dht-entry-point")
@dht_entry_point.setter
def dht_entry_point(self, value):
self.set("dht-entry-point", value)
@property
def dht_entry_point6(self):
"""
Set host and port as an entry point to IPv6 DHT network (:).
Returns:
str
"""
return self.get("dht-entry-point6")
@dht_entry_point6.setter
def dht_entry_point6(self, value):
self.set("dht-entry-point6", value)
@property
def dht_file_path(self):
"""
Change the IPv4 DHT routing table file to PATH.
Default: $HOME/.aria2/dht.dat if present, otherwise $XDG_CACHE_HOME/aria2/dht.dat.
Returns:
str
"""
return self.get("dht-file-path")
@dht_file_path.setter
def dht_file_path(self, value):
self.set("dht-file-path", value)
@property
def dht_file_path6(self):
"""
Change the IPv6 DHT routing table file to PATH.
Default: $HOME/.aria2/dht6.dat if present, otherwise $XDG_CACHE_HOME/aria2/dht6.dat.
Returns:
str
"""
return self.get("dht-file-path6")
@dht_file_path6.setter
def dht_file_path6(self, value):
self.set("dht-file-path6", value)
@property
def dht_listen_addr6(self):
"""
Specify address to bind socket for IPv6 DHT.
It should be a global unicast IPv6 address of the host.
Returns:
str
"""
return self.get("dht-listen-addr6")
@dht_listen_addr6.setter
def dht_listen_addr6(self, value):
self.set("dht-listen-addr6", value)
@property
def dht_listen_port(self):
"""
Set UDP listening port used by DHT(IPv4, IPv6) and UDP tracker.
Multiple ports can be specified by using ,, for example: 6881,6885. You can also use - to specify a range:
6881-6999. , and - can be used together. Default: 6881-6999.
NOTE:
Make sure that the specified ports are open for incoming UDP traffic.
Returns:
str
"""
return self.get("dht-listen-port")
@dht_listen_port.setter
def dht_listen_port(self, value):
self.set("dht-listen-port", value)
@property
def dht_message_timeout(self):
"""
Set timeout in seconds.
Default: 10.
Returns:
int
"""
return int(self.get("dht-message-timeout"))
@dht_message_timeout.setter
def dht_message_timeout(self, value):
self.set("dht-message-timeout", value)
@property
def enable_dht(self):
"""
Enable IPv4 DHT functionality.
It also enables UDP tracker support. If a private flag is set in a torrent, aria2 doesn't use DHT for that
download even if true is given. Default: true.
Returns:
bool
"""
return bool_or_value(self.get("enable-dht"))
@enable_dht.setter
def enable_dht(self, value):
self.set("enable-dht", bool_to_str(value))
@property
def enable_dht6(self):
"""
Enable IPv6 DHT functionality.
If a private flag is set in a torrent, aria2 doesn't use DHT for that download even if true is given. Use
--dht-listen-port option to specify port number to listen on. See also --dht-listen-addr6 option.
Returns:
bool
"""
return bool_or_value(self.get("enable-dht6"))
@enable_dht6.setter
def enable_dht6(self, value):
self.set("enable-dht6", bool_to_str(value))
@property
def enable_peer_exchange(self):
"""
Enable Peer Exchange extension.
If a private flag is set in a torrent, this feature is disabled for that download even if true is given.
Default: true.
Returns:
bool
"""
return bool_or_value(self.get("enable-peer-exchange"))
@enable_peer_exchange.setter
def enable_peer_exchange(self, value):
self.set("enable-peer-exchange", bool_to_str(value))
@property
def follow_torrent(self):
"""
If true or mem is specified, when a file whose suffix is .torrent or content type is application/x-bittorrent
is downloaded, aria2 parses it as a torrent file and downloads files mentioned in it.
If mem is specified, a torrent file is not written to the disk, but is just kept in memory. If false is
specified, the .torrent file is downloaded to the disk, but is not parsed as a torrent and its contents are
not downloaded. Default: true.
Returns:
str
"""
return self.get("follow-torrent")
@follow_torrent.setter
def follow_torrent(self, value):
self.set("follow-torrent", value)
@property
def index_out(self):
"""
Set file path for file with index=INDEX (=).
You can find the file index using the --show-files option. PATH is a relative path to the path specified in
--dir option. You can use this option multiple times. Using this option, you can specify the output file
names of BitTorrent downloads.
Returns:
str
"""
return self.get("index-out")
@index_out.setter
def index_out(self, value):
self.set("index-out", value)
@property
def listen_port(self):
"""
Set TCP port number for BitTorrent downloads.
Multiple ports can be specified by using, for example: 6881,6885. You can also use - to specify a range:
6881-6999. , and - can be used together: 6881-6889, 6999. Default: 6881-6999
NOTE:
Make sure that the specified ports are open for incoming TCP traffic.
Returns:
str
"""
return self.get("listen-port")
@listen_port.setter
def listen_port(self, value):
self.set("listen-port", value)
@property
def max_overall_upload_limit(self):
"""
Set max overall upload speed in bytes/sec.
0 means unrestricted. You can append K or M (1K = 1024, 1M = 1024K). To limit the upload speed per torrent,
use --max-upload-limit option. Default: 0.
Returns:
int
"""
return int(self.get("max-overall-upload-limit"))
@max_overall_upload_limit.setter
def max_overall_upload_limit(self, value):
self.set("max-overall-upload-limit", value)
@property
def max_upload_limit(self):
"""
Set max upload speed per each torrent in bytes/sec.
0 means unrestricted. You can append K or M (1K = 1024, 1M = 1024K). To limit the overall upload speed,
use --max-overall-upload-limit option. Default: 0.
Returns:
int
"""
return int(self.get("max-upload-limit"))
@max_upload_limit.setter
def max_upload_limit(self, value):
self.set("max-upload-limit", value)
@property
def peer_id_prefix(self):
"""
Specify the prefix of peer ID.
The peer ID in BitTorrent is 20 byte length. If more than 20 bytes are specified, only first 20 bytes are
used. If less than 20 bytes are specified, random byte data are added to make its length 20 bytes.
Default: A2-$MAJOR-$MINOR-$PATCH-, $MAJOR, $MINOR and $PATCH are replaced by major, minor and patch
version number respectively. For instance, aria2 version 1.18.8 has prefix ID A2-1-18-8-.
Returns:
str
"""
return self.get("peer-id-prefix")
@peer_id_prefix.setter
def peer_id_prefix(self, value):
self.set("peer-id-prefix", value)
@property
def seed_ratio(self):
"""
Specify share ratio.
Seed completed torrents until share ratio reaches RATIO. You are strongly encouraged to specify equals or
more than 1.0 here. Specify 0.0 if you intend to do seeding regardless of share ratio. If --seed-time option
is specified along with this option, seeding ends when at least one of the conditions is satisfied. Default:
1.0.
Returns:
float
"""
return self.get("seed-ratio")
@seed_ratio.setter
def seed_ratio(self, value):
self.set("seed-ratio", value)
@property
def seed_time(self):
"""
Specify seeding time in (fractional) minutes.
Also see the --seed-ratio option.
NOTE:
Specifying --seed-time=0 disables seeding after download completed.
Returns:
float
"""
return self.get("seed-time")
@seed_time.setter
def seed_time(self, value):
self.set("seed-time", value)
@property
def torrent_file(self):
"""
The path to the ".torrent" file.
You are not required to use this option because you can specify ".torrent" files without --torrent-file.
Returns:
str
"""
return self.get("torrent-file")
@torrent_file.setter
def torrent_file(self, value):
self.set("torrent-file", value)
# Metalink Specific Options
@property
def follow_metalink(self):
"""
If true or mem is specified, when a file whose suffix is .meta4 or .metalink or content type of
application/metalink4+xml or application/metalink+xml is downloaded, aria2 parses it as a metalink file and
downloads files mentioned in it.
If mem is specified, a metalink file is not written to the disk, but is just kept in memory. If false is
specified, the .metalink file is downloaded to the disk, but is not parsed as a metalink file and its
contents are not downloaded. Default: true.
Returns:
str
"""
return self.get("follow-metalink")
@follow_metalink.setter
def follow_metalink(self, value):
self.set("follow-metalink", value)
@property
def metalink_base_uri(self):
"""
Specify base URI to resolve relative URI in metalink:url and metalink:metaurl element in a metalink file
stored in local disk.
If URI points to a directory, URI must end with /.
Returns:
str
"""
return self.get("metalink-base-uri")
@metalink_base_uri.setter
def metalink_base_uri(self, value):
self.set("metalink-base-uri", value)
@property
def metalink_file(self):
"""
The file path to ".meta4" and ".metalink" file.
Reads input from stdin when - is specified. You are not required to use this option because you can specify
".metalink" files without --metalink-file.
Returns:
str
"""
return self.get("metalink-file")
@metalink_file.setter
def metalink_file(self, value):
self.set("metalink-file", value)
@property
def metalink_language(self):
"""
The language of the file to download.
Returns:
str
"""
return self.get("metalink-language")
@metalink_language.setter
def metalink_language(self, value):
self.set("metalink-language", value)
@property
def metalink_location(self):
"""
The location of the preferred server.
A comma-delimited list of locations is acceptable, for example, jp,us.
Returns:
list of str
"""
return self.get("metalink-location")
@metalink_location.setter
def metalink_location(self, value):
self.set("metalink-location", value)
@property
def metalink_os(self):
"""
The operating system of the file to download.
Returns:
str
"""
return self.get("metalink-os")
@metalink_os.setter
def metalink_os(self, value):
self.set("metalink-os", value)
@property
def metalink_version(self):
"""
The version of the file to download.
Returns:
str
"""
return self.get("metalink-version")
@metalink_version.setter
def metalink_version(self, value):
self.set("metalink-version", value)
@property
def metalink_preferred_protocol(self):
"""
Specify preferred protocol.
The possible values are http, https, ftp and none. Specify none to disable this feature. Default: none.
Returns:
str
"""
return self.get("metalink-preferred-protocol")
@metalink_preferred_protocol.setter
def metalink_preferred_protocol(self, value):
self.set("metalink-preferred-protocol", value)
@property
def metalink_enable_unique_protocol(self):
"""
If true is given and several protocols are available for a mirror in a metalink file, aria2 uses one of them.
Use --metalink-preferred-protocol option to specify the preference of protocol. Default: true.
Returns:
bool
"""
return bool_or_value(self.get("metalink_enable_unique_protocol"))
@metalink_enable_unique_protocol.setter
def metalink_enable_unique_protocol(self, value):
self.set("metalink_enable_unique_protocol", bool_to_str(value))
# RPC Options
@property
def enable_rpc(self):
"""
Enable JSON-RPC/XML-RPC server.
It is strongly recommended to set secret authorization token using --rpc-secret option. See also
--rpc-listen-port option. Default: false
Returns:
bool
"""
return bool_or_value(self.get("enable-rpc"))
@enable_rpc.setter
def enable_rpc(self, value):
self.set("enable-rpc", bool_to_str(value))
@property
def pause(self):
"""
Pause download after added.
This option is effective only when --enable-rpc=true is given. Default: false.
Returns:
bool
"""
return bool_or_value(self.get("pause"))
@pause.setter
def pause(self, value):
self.set("pause", bool_to_str(value))
@property
def pause_metadata(self):
"""
Pause downloads created as a result of metadata download.
There are 3 types of metadata downloads in aria2: (1) downloading .torrent file. (2) downloading torrent
metadata using magnet link. (3) downloading metalink file. These metadata downloads will generate downloads
using their metadata. This option pauses these subsequent downloads. This option is effective only when
--enable-rpc=true is given. Default: false.
Returns:
bool
"""
return bool_or_value(self.get("pause-metadata"))
@pause_metadata.setter
def pause_metadata(self, value):
self.set("pause-metadata", bool_to_str(value))
@property
def rpc_allow_origin_all(self):
"""
Add Access-Control-Allow-Origin header field with value * to the RPC response.
Default: false.
Returns:
bool
"""
return bool_or_value(self.get("rpc-allow-origin-all"))
@rpc_allow_origin_all.setter
def rpc_allow_origin_all(self, value):
self.set("rpc-allow-origin-all", bool_to_str(value))
@property
def rpc_certificate(self):
"""
Use the certificate in FILE for RPC server.
The certificate must be either in PKCS12 (.p12, .pfx) or in PEM format.
PKCS12 files must contain the certificate, a key and optionally a chain of additional certificates. Only
PKCS12 files with a blank import password can be opened!
When using PEM, you have to specify the private key via --rpc-private-key as well. Use --rpc-secure option
to enable encryption.
NOTE:
WinTLS does not support PEM files at the moment. Users have to use PKCS12 files.
NOTE:
AppleTLS users should use the KeyChain Access utility to first generate a self-signed SSL-Server
certificate, e.g. using the wizard, and get the SHA-1 fingerprint from the Information dialog
corresponding to that new certificate. To start aria2c with --rpc-secure use --rpc-certificate=.
Alternatively PKCS12 files are also supported. PEM files, however, are not supported.
Returns:
str
"""
return self.get("rpc-certificate")
@rpc_certificate.setter
def rpc_certificate(self, value):
self.set("rpc-certificate", value)
@property
def rpc_listen_all(self):
"""
Listen incoming JSON-RPC/XML-RPC requests on all network interfaces.
If false is given, listen only on local loopback interface. Default: false.
Returns:
bool
"""
return bool_or_value(self.get("rpc-listen-all"))
@rpc_listen_all.setter
def rpc_listen_all(self, value):
self.set("rpc-listen-all", bool_to_str(value))
@property
def rpc_listen_port(self):
"""
Specify a port number for JSON-RPC/XML-RPC server to listen to.
Possible Values: 1024-65535. Default: 6800.
Returns:
int
"""
return int(self.get("rpc-listen-port"))
@rpc_listen_port.setter
def rpc_listen_port(self, value):
self.set("rpc-listen-port", value)
@property
def rpc_max_request_size(self):
"""
Set max size of JSON-RPC/XML-RPC request in bytes.
If aria2 detects the request is more than SIZE bytes, it drops connection. Default: 2M.
Returns:
str
"""
return self.get("rpc-max-request-size")
@rpc_max_request_size.setter
def rpc_max_request_size(self, value):
self.set("rpc-max-request-size", value)
@property
def rpc_passwd(self):
"""
Set JSON-RPC/XML-RPC password.
WARNING:
--rpc-passwd option will be deprecated in the future release. Migrate to --rpc-secret option as soon as
possible.
Returns:
str
"""
return self.get("rpc-passwd")
@rpc_passwd.setter
def rpc_passwd(self, value):
self.set("rpc-passwd", value)
@property
def rpc_private_key(self):
"""
Use the private key in FILE for RPC server.
The private key must be decrypted and in PEM format. Use --rpc-secure option to enable encryption. See also
--rpc-certificate option.
Returns:
str
"""
return self.get("rpc-private-key")
@rpc_private_key.setter
def rpc_private_key(self, value):
self.set("rpc-private-key", value)
@property
def rpc_save_upload_metadata(self):
"""
Save the uploaded torrent or metalink meta data in the directory specified by --dir option.
The file name consists of SHA-1 hash hex string of meta data plus extension. For torrent, the extension is
'.torrent'. For metalink, it is '.meta4'. If false is given to this option, the downloads added by
aria2.addTorrent() or aria2.addMetalink() will not be saved by --save-session option. Default: true.
Returns:
bool
"""
return bool_or_value(self.get("rpc-save-upload-metadata"))
@rpc_save_upload_metadata.setter
def rpc_save_upload_metadata(self, value):
self.set("rpc-save-upload-metadata", bool_to_str(value))
@property
def rpc_secret(self):
"""
Set RPC secret authorization token.
Read RPC authorization secret token to know how this option value is used.
Returns:
str
"""
return self.get("rpc-secret")
@rpc_secret.setter
def rpc_secret(self, value):
self.set("rpc-secret", value)
@property
def rpc_secure(self):
"""
RPC transport will be encrypted by SSL/TLS.
The RPC clients must use https scheme to access the server. For WebSocket client, use wss scheme. Use
--rpc-certificate and --rpc-private-key options to specify the server certificate and private key.
Returns:
bool
"""
return bool_or_value(self.get("rpc-secure"))
@rpc_secure.setter
def rpc_secure(self, value):
self.set("rpc-secure", bool_to_str(value))
@property
def rpc_user(self):
"""
Set JSON-RPC/XML-RPC user.
WARNING:
--rpc-user option will be deprecated in the future release. Migrate to --rpc-secret option as soon as
possible.
Returns:
str
"""
return self.get("rpc-user")
@rpc_user.setter
def rpc_user(self, value):
self.set("rpc-user", value)
# Advanced Options
@property
def allow_overwrite(self):
"""
Restart download from scratch if the corresponding control file doesn't exist.
See also --auto-file-renaming option. Default: false.
Returns:
bool
"""
return bool_or_value(self.get("allow-overwrite"))
@allow_overwrite.setter
def allow_overwrite(self, value):
self.set("allow-overwrite", bool_to_str(value))
@property
def allow_piece_length_change(self):
"""
If false is given, aria2 aborts download when a piece length is different from one in a control file.
If true is given, you can proceed but some download progress will be lost. Default: false.
Returns:
bool
"""
return bool_or_value(self.get("allow-piece-length-change"))
@allow_piece_length_change.setter
def allow_piece_length_change(self, value):
self.set("allow-piece-length-change", bool_to_str(value))
@property
def always_resume(self):
"""
Always resume download.
If true is given, aria2 always tries to resume download and if resume is not possible, aborts download. If
false is given, when all given URIs do not support resume or aria2 encounters N URIs which does not support
resume (N is the value specified using --max-resume-failure-tries option), aria2 downloads file from scratch.
See --max-resume-failure-tries option. Default: true.
Returns:
bool
"""
return bool_or_value(self.get("always-resume"))
@always_resume.setter
def always_resume(self, value):
self.set("always-resume", bool_to_str(value))
@property
def async_dns(self):
"""
Enable asynchronous DNS.
Default: true.
Returns:
bool
"""
return bool_or_value(self.get("async-dns"))
@async_dns.setter
def async_dns(self, value):
self.set("async-dns", bool_to_str(value))
@property
def async_dns_server(self):
"""
Comma separated list of DNS server address used in asynchronous DNS resolver.
Usually asynchronous DNS resolver reads DNS server addresses from /etc/resolv.conf. When this option is used,
it uses DNS servers specified in this option instead of ones in /etc/resolv.conf. You can specify both IPv4
and IPv6 address. This option is useful when the system does not have /etc/resolv.conf and user does not have
the permission to create it.
Returns:
list of str
"""
return self.get("async-dns-server")
@async_dns_server.setter
def async_dns_server(self, value):
self.set("async-dns-server", value)
@property
def auto_file_renaming(self):
"""
Rename file name if the same file already exists.
This option works only in HTTP(S)/FTP download. The new file name has a dot and a number(1..9999) appended
after the name, but before the file extension, if any. Default: true.
Returns:
bool
"""
return bool_or_value(self.get("auto-file-renaming"))
@auto_file_renaming.setter
def auto_file_renaming(self, value):
self.set("auto-file-renaming", bool_to_str(value))
@property
def auto_save_interval(self):
"""
Save a control file(*.aria2) every SEC seconds.
If 0 is given, a control file is not saved during download. aria2 saves a control file when it stops
regardless of the value. The possible values are between 0 to 600. Default: 60.
Returns:
int
"""
return int(self.get("auto-save-interval"))
@auto_save_interval.setter
def auto_save_interval(self, value):
self.set("auto-save-interval", value)
@property
def conditional_get(self):
"""
Download file only when the local file is older than remote file.
This function only works with HTTP(S) downloads only. It does not work if file size is specified in Metalink.
It also ignores Content-Disposition header. If a control file exists, this option will be ignored. This
function uses If-Modified-Since header to get only newer file conditionally. When getting modification time
of local file, it uses user supplied file name (see --out option) or file name part in URI if --out is not
specified. To overwrite existing file, --allow-overwrite is required. Default: false.
Returns:
bool
"""
return bool_or_value(self.get("conditional-get"))
@conditional_get.setter
def conditional_get(self, value):
self.set("conditional-get", bool_to_str(value))
@property
def conf_path(self):
"""
Change the configuration file path to PATH.
Default: $HOME/.aria2/aria2.conf if present, otherwise $XDG_CONFIG_HOME/aria2/aria2.conf.
Returns:
str
"""
return self.get("conf-path")
@conf_path.setter
def conf_path(self, value):
self.set("conf-path", value)
@property
def console_log_level(self):
"""
Set log level to output to console.
LEVEL is either debug, info, notice, warn or error. Default: notice.
Returns:
str
"""
return self.get("console-log-level")
@console_log_level.setter
def console_log_level(self, value):
self.set("console-log-level", value)
@property
def daemon(self):
"""
Run as daemon.
The current working directory will be changed to / and standard input, standard output and standard error
will be redirected to /dev/null. Default: false.
Returns:
bool
"""
return bool_or_value(self.get("daemon"))
@daemon.setter
def daemon(self, value):
self.set("daemon", bool_to_str(value))
@property
def deferred_input(self):
"""
If true is given, aria2 does not read all URIs and options from file specified by --input-file option at
startup, but it reads one by one when it needs later.
This may reduce memory usage if input file contains a lot of URIs to download. If false is given, aria2 reads
all URIs and options at startup. Default: false.
WARNING:
--deferred-input option will be disabled when --save-session is used together.
Returns:
bool
"""
return bool_or_value(self.get("deferred-input"))
@deferred_input.setter
def deferred_input(self, value):
self.set("deferred-input", bool_to_str(value))
@property
def disable_ipv6(self):
"""
Disable IPv6.
This is useful if you have to use broken DNS and want to avoid terribly slow AAAA record lookup. Default: false.
Returns:
bool
"""
return bool_or_value(self.get("disable-ipv6"))
@disable_ipv6.setter
def disable_ipv6(self, value):
self.set("disable-ipv6", bool_to_str(value))
@property
def disk_cache(self):
"""
Enable disk cache.
If SIZE is 0, the disk cache is disabled. This feature caches the downloaded data in memory, which grows to
at most SIZE bytes. The cache storage is created for aria2 instance and shared by all downloads. The one
advantage of the disk cache is reduce the disk I/O because the data are written in larger unit and it is
reordered by the offset of the file. If hash checking is involved and the data are cached in memory,
we don't need to read them from the disk. SIZE can include K or M (1K = 1024, 1M = 1024K). Default: 16M.
Returns:
int
"""
return int(self.get("disk-cache"))
@disk_cache.setter
def disk_cache(self, value):
self.set("disk-cache", value)
@property
def download_result(self):
"""
This option changes the way Download Results is formatted.
If OPT is default, print GID, status, average download speed and path/URI. If multiple files are involved,
path/URI of first requested file is printed and remaining ones are omitted. If OPT is full, print GID,
status, average download speed, percentage of progress and path/URI. The percentage of progress and path/URI
are printed for each requested file in each row. If OPT is hide, Download Results is hidden. Default: default.
Returns:
str
"""
return self.get("download-result")
@download_result.setter
def download_result(self, value):
self.set("download-result", value)
@property
def dscp(self):
"""
Set DSCP value in outgoing IP packets of BitTorrent traffic for QoS.
This parameter sets only DSCP bits in TOS field of IP packets, not the whole field. If you take values from
/usr/include/netinet/ip.h divide them by 4 (otherwise values would be incorrect, e.g. your CS1 class would
turn into CS4). If you take commonly used values from RFC, network vendors' documentation, Wikipedia or any
other source, use them as they are.
Returns:
str
"""
return self.get("dscp")
@dscp.setter
def dscp(self, value):
self.set("dscp", value)
@property
def rlimit_nofile(self):
"""
Set the soft limit of open file descriptors.
This open will only have effect when:
a. The system supports it (posix)
b. The limit does not exceed the hard limit.
c. The specified limit is larger than the current soft limit.
This is equivalent to setting nofile via ulimit, except that it will never decrease the limit.
This option is only available on systems supporting the rlimit API.
Returns:
int
"""
return int(self.get("rlimit-nofile"))
@rlimit_nofile.setter
def rlimit_nofile(self, value):
self.set("rlimit-nofile", value)
@property
def enable_color(self):
"""
Enable color output for a terminal.
Default: true.
Returns:
bool
"""
return bool_or_value(self.get("enable-color"))
@enable_color.setter
def enable_color(self, value):
self.set("enable-color", bool_to_str(value))
@property
def enable_mmap(self):
"""
Map files into memory.
This option may not work if the file space is not pre-allocated. See --file-allocation. Default: false.
Returns:
bool
"""
return bool_or_value(self.get("enable-mmap"))
@enable_mmap.setter
def enable_mmap(self, value):
self.set("enable-mmap", bool_to_str(value))
@property
def event_poll(self):
"""
Specify the method for polling events.
The possible values are epoll, kqueue, port, poll and select. For each epoll, kqueue, port and poll,
it is available if system supports it. epoll is available on recent Linux. kqueue is available on various
*BSD systems including Mac OS X. port is available on Open Solaris. The default value may vary depending on
the system you use.
Returns:
str
"""
return self.get("event-poll")
@event_poll.setter
def event_poll(self, value):
self.set("event-poll", value)
@property
def file_allocation(self):
"""
Specify file allocation method.
Possible Values: none, prealloc, trunc, falloc.
none: doesn't pre-allocate file space.
prealloc: pre-allocates file space before download begins. This may take some time depending on the size of
the file.
falloc: If you are using newer file systems such as ext4 (with extents support), btrfs, xfs or NTFS(MinGW
build only), falloc is your best choice. It allocates large(few GiB) files almost instantly. Don't use falloc
with legacy file systems such as ext3 and FAT32 because it takes almost same time as prealloc and it blocks
aria2 entirely until allocation finishes. falloc may not be available if your system doesn't have
posix_fallocate(3) function.
trunc: uses ftruncate(2) system call or platform-specific counterpart to truncate a file to a specified length.
Default: prealloc.
WARNING:
Using trunc seemingly allocates disk space very quickly, but what it actually does is that it sets file
length metadata in file system, and does not allocate disk space at all. This means that it does not help
avoiding fragmentation.
NOTE:
In multi file torrent downloads, the files adjacent forward to the specified files are also allocated if
they share the same piece.
Returns:
str
"""
return self.get("file-allocation")
@file_allocation.setter
def file_allocation(self, value):
self.set("file-allocation", value)
@property
def force_save(self):
"""
Save download with --save-session option even if the download is completed or removed.
This option also saves control file in that situations. This may be useful to save BitTorrent seeding which
is recognized as completed state. Default: false.
Returns:
bool
"""
return bool_or_value(self.get("force-save"))
@force_save.setter
def force_save(self, value):
self.set("force-save", bool_to_str(value))
@property
def save_not_found(self):
"""
Save download with --save-session option even if the file was not found on the server.
This option also saves control file in that situations. Default: true.
Returns:
bool
"""
return bool_or_value(self.get("save-not-found"))
@save_not_found.setter
def save_not_found(self, value):
self.set("save-not-found", bool_to_str(value))
@property
def gid(self):
"""
Set GID manually.
aria2 identifies each download by the ID called GID. The GID must be hex string of 16 characters,
thus [0-9a-zA-Z] are allowed and leading zeros must not be stripped. The GID all 0 is reserved and must not
be used. The GID must be unique, otherwise error is reported and the download is not added. This option is
useful when restoring the sessions saved using --save-session option. If this option is not used, new GID is
generated by aria2.
Returns:
str
"""
return self.get("gid")
@gid.setter
def gid(self, value):
self.set("gid", value)
@property
def hash_check_only(self):
"""
If true is given, after hash check using --check-integrity option, abort download whether or not download
is complete.
Default: false.
Returns:
bool
"""
return bool_or_value(self.get("hash-check-only"))
@hash_check_only.setter
def hash_check_only(self, value):
self.set("hash-check-only", bool_to_str(value))
@property
def human_readable(self):
"""
Print sizes and speed in human readable format (e.g., 1.2Ki, 3.4Mi) in the console readout.
Default: true.
Returns:
bool
"""
return bool_or_value(self.get("human-readable"))
@human_readable.setter
def human_readable(self, value):
self.set("human-readable", bool_to_str(value))
@property
def interface(self):
"""
Bind sockets to given interface.
You can specify interface name, IP address and host name. Possible Values: interface, IP address, host name.
NOTE:
If an interface has multiple addresses, it is highly recommended to specify IP address explicitly. See
also --disable-ipv6. If your system doesn't have getifaddrs(3), this option doesn't accept interface
name.
Returns:
str
"""
return self.get("interface")
@interface.setter
def interface(self, value):
self.set("interface", value)
@property
def keep_unfinished_download_result(self):
"""
Keep unfinished download results even if doing so exceeds --max-download-result.
This is useful if all unfinished downloads must be saved in session file (see --save-session option). Please
keep in mind that there is no upper bound to the number of unfinished download result to keep. If that is
undesirable, turn this option off. Default: true.
Returns:
bool
"""
return bool_or_value(self.get("keep_unfinished_download_result"))
@keep_unfinished_download_result.setter
def keep_unfinished_download_result(self, value):
self.set("keep_unfinished_download_result", bool_to_str(value))
@property
def max_download_result(self):
"""
Set maximum number of download result kept in memory.
The download results are completed/error/removed downloads. The download results are stored in FIFO queue and
it can store at most NUM download results. When queue is full and new download result is created,
oldest download result is removed from the front of the queue and new one is pushed to the back. Setting big
number in this option may result high memory consumption after thousands of downloads. Specifying 0 means no
download result is kept. Note that unfinished downloads are kept in memory regardless of this option value.
See --keep-unfinished-download-result option. Default: 1000.
Returns:
int
"""
return int(self.get("max-download-result"))
@max_download_result.setter
def max_download_result(self, value):
self.set("max-download-result", value)
@property
def max_mmap_limit(self):
"""
Set the maximum file size to enable mmap (see --enable-mmap option).
The file size is determined by the sum of all files contained in one download. For example, if a download
contains 5 files, then file size is the total size of those files. If file size is strictly greater than the
size specified in this option, mmap will be disabled. Default: 9223372036854775807.
Returns:
int
"""
return int(self.get("max-mmap-limit"))
@max_mmap_limit.setter
def max_mmap_limit(self, value):
self.set("max-mmap-limit", value)
@property
def max_resume_failure_tries(self):
"""
When used with --always-resume=false, aria2 downloads file from scratch when aria2 detects N number of
URIs that does not support resume.
If N is 0, aria2 downloads file from scratch when all given URIs do not support resume. See --always-resume
option. Default: 0.
Returns:
int
"""
return int(self.get("max-resume-failure-tries"))
@max_resume_failure_tries.setter
def max_resume_failure_tries(self, value):
self.set("max-resume-failure-tries", value)
@property
def min_tls_version(self):
"""
Specify minimum SSL/TLS version to enable.
Possible Values: SSLv3, TLSv1, TLSv1.1, TLSv1.2. Default: TLSv1.
Returns:
str
"""
return self.get("min-tls-version")
@min_tls_version.setter
def min_tls_version(self, value):
self.set("min-tls-version", value)
@property
def multiple_interface(self):
"""
Comma separated list of interfaces to bind sockets to.
Requests will be split among the interfaces to achieve link aggregation. You can specify interface name,
IP address and hostname. If --interface is used, this option will be ignored. Possible Values: interface,
IP address, hostname.
Returns:
list of str
"""
return self.get("multiple-interface")
@multiple_interface.setter
def multiple_interface(self, value):
self.set("multiple-interface", value)
@property
def log_level(self):
"""
Set log level to output.
LEVEL is either debug, info, notice, warn or error. Default: debug.
Returns:
str
"""
return self.get("log-level")
@log_level.setter
def log_level(self, value):
self.set("log-level", value)
@property
def on_bt_download_complete(self):
"""
For BitTorrent, a command specified in --on-download-complete is called after download completed and
seeding is over.
On the other hand, this option set the command to be executed after download completed but before seeding.
See Event Hook for more details about COMMAND. Possible Values: /path/to/command.
Returns:
str
"""
return self.get("on-bt-download-complete")
@on_bt_download_complete.setter
def on_bt_download_complete(self, value):
self.set("on-bt-download-complete", value)
@property
def on_download_complete(self):
"""
Set the command to be executed after download completed.
See See Event Hook for more details about COMMAND. See also --on-download-stop option. Possible Values:
/path/to/command.
Returns:
str
"""
return self.get("on-download-complete")
@on_download_complete.setter
def on_download_complete(self, value):
self.set("on-download-complete", value)
@property
def on_download_error(self):
"""
Set the command to be executed after download aborted due to error.
See Event Hook for more details about COMMAND. See also --on-download-stop option. Possible Values:
/path/to/command.
Returns:
str
"""
return self.get("on-download-error")
@on_download_error.setter
def on_download_error(self, value):
self.set("on-download-error", value)
@property
def on_download_pause(self):
"""
Set the command to be executed after download was paused.
See Event Hook for more details about COMMAND. Possible Values: /path/to/command.
Returns:
str
"""
return self.get("on-download-pause")
@on_download_pause.setter
def on_download_pause(self, value):
self.set("on-download-pause", value)
@property
def on_download_start(self):
"""
Set the command to be executed after download got started.
See Event Hook for more details about COMMAND. Possible Values: /path/to/command.
Returns:
str
"""
return self.get("on-download-start")
@on_download_start.setter
def on_download_start(self, value):
self.set("on-download-start", value)
@property
def on_download_stop(self):
"""
Set the command to be executed after download stopped.
You can override the command to be executed for particular download result using --on-download-complete and
--on-download-error. If they are specified, command specified in this option is not executed. See Event Hook
for more details about COMMAND. Possible Values: /path/to/command.
Returns:
str
"""
return self.get("on-download-stop")
@on_download_stop.setter
def on_download_stop(self, value):
self.set("on-download-stop", value)
@property
def optimize_concurrent_downloads(self):
"""
Optimizes the number of concurrent downloads according to the bandwidth available (true|false|:).
aria2 uses the download speed observed in the previous downloads to adapt the number of downloads launched in
parallel according to the rule N = A + B Log10(speed in Mbps). The coefficients A and B can be customized in
the option arguments with A and B separated by a colon. The default values (A=5, B=25) lead to using
typically 5 parallel downloads on 1Mbps networks and above 50 on 100Mbps networks. The number of parallel
downloads remains constrained under the maximum defined by the --max-concurrent-downloads parameter. Default:
false.
Returns:
str
"""
return self.get("optimize-concurrent-downloads")
@optimize_concurrent_downloads.setter
def optimize_concurrent_downloads(self, value):
self.set("optimize-concurrent-downloads", value)
@property
def piece_length(self):
"""
Set a piece length for HTTP/FTP downloads.
This is the boundary when aria2 splits a file. All splits occur at multiple of this length. This option will
be ignored in BitTorrent downloads. It will be also ignored if Metalink file contains piece hashes. Default: 1M.
NOTE:
The possible use case of --piece-length option is change the request range in one HTTP pipelined
request. To enable HTTP pipelining use --enable-http-pipelining.
Returns:
str
"""
return self.get("piece-length")
@piece_length.setter
def piece_length(self, value):
self.set("piece-length", value)
@property
def show_console_readout(self):
"""
Show console readout.
Default: true.
Returns:
bool
"""
return bool_or_value(self.get("show-console-readout"))
@show_console_readout.setter
def show_console_readout(self, value):
self.set("show-console-readout", bool_to_str(value))
@property
def stderr(self):
"""
Redirect all console output that would be otherwise printed in stdout to stderr.
Default: false.
Returns:
bool
"""
return bool_or_value(self.get("stderr"))
@stderr.setter
def stderr(self, value):
self.set("stderr", bool_to_str(value))
@property
def summary_interval(self):
"""
Set interval in seconds to output download progress summary.
Setting 0 suppresses the output. Default: 60.
Returns:
int
"""
return int(self.get("summary-interval"))
@summary_interval.setter
def summary_interval(self, value):
self.set("summary-interval", value)
@property
def force_sequential(self):
"""
Fetch URIs in the command-line sequentially and download each URI in a separate session, like the usual
command-line download utilities.
Default: false.
Returns:
bool
"""
return bool_or_value(self.get("force-sequential"))
@force_sequential.setter
def force_sequential(self, value):
self.set("force-sequential", bool_to_str(value))
@property
def max_overall_download_limit(self):
"""
Set max overall download speed in bytes/sec.
0 means unrestricted. You can append K or M (1K = 1024, 1M = 1024K). To limit the download speed per
download, use --max-download-limit option. Default: 0.
Returns:
int
"""
return int(self.get("max-overall-download-limit"))
@max_overall_download_limit.setter
def max_overall_download_limit(self, value):
self.set("max-overall-download-limit", value)
@property
def max_download_limit(self):
"""
Set max download speed per each download in bytes/sec.
0 means unrestricted. You can append K or M (1K = 1024, 1M = 1024K). To limit the overall download speed,
use --max-overall-download-limit option. Default: 0.
Returns:
int
"""
return int(self.get("max-download-limit"))
@max_download_limit.setter
def max_download_limit(self, value):
self.set("max-download-limit", value)
@property
def no_conf(self):
"""
Disable loading aria2.conf file.
Returns:
bool
"""
return bool_or_value(self.get("no-conf"))
@no_conf.setter
def no_conf(self, value):
self.set("no-conf", bool_to_str(value))
@property
def no_file_allocation_limit(self):
"""
No file allocation is made for files whose size is smaller than SIZE.
You can append K or M (1K = 1024, 1M = 1024K). Default: 5M.
Returns:
int
"""
return int(self.get("no-file-allocation-limit"))
@no_file_allocation_limit.setter
def no_file_allocation_limit(self, value):
self.set("no-file-allocation-limit", value)
@property
def parameterized_uri(self):
"""
Enable parameterized URI support.
You can specify set of parts: http://{sv1,sv2,sv3}/foo.iso. Also you can specify numeric sequences with step
counter: http://host/image[000-100:2].img. A step counter can be omitted. If all URIs do not point to the
same file, such as the second example above, -Z option is required. Default: false.
Returns:
bool
"""
return bool_or_value(self.get("parameterized-uri"))
@parameterized_uri.setter
def parameterized_uri(self, value):
self.set("parameterized-uri", bool_to_str(value))
@property
def quiet(self):
"""
Make aria2 quiet (no console output).
Default: false.
Returns:
bool
"""
return bool_or_value(self.get("quiet"))
@quiet.setter
def quiet(self, value):
self.set("quiet", bool_to_str(value))
@property
def realtime_chunk_checksum(self):
"""
Validate chunk of data by calculating checksum while downloading a file if chunk checksums are provided.
Default: true.
Returns:
bool
"""
return bool_or_value(self.get("realtime-chunk-checksum"))
@realtime_chunk_checksum.setter
def realtime_chunk_checksum(self, value):
self.set("realtime-chunk-checksum", bool_to_str(value))
@property
def remove_control_file(self):
"""
Remove control file before download.
Using with --allow-overwrite=true, download always starts from scratch. This will be useful for users behind
proxy server which disables resume.
Returns:
bool
"""
return bool_or_value(self.get("remove-control-file"))
@remove_control_file.setter
def remove_control_file(self, value):
self.set("remove-control-file", bool_to_str(value))
@property
def save_session(self):
"""
Save error/unfinished downloads to FILE on exit.
You can pass this output file to aria2c with --input-file option on restart. If you like the output to be
gzipped append a .gz extension to the file name. Please note that downloads added by aria2.addTorrent() and
aria2.addMetalink() RPC method and whose meta data could not be saved as a file are not saved. Downloads
removed using aria2.remove() and aria2.forceRemove() will not be saved. GID is also saved with gid,
but there are some restrictions, see below.
NOTE:
Normally, GID of the download itself is saved. But some downloads use meta data (e.g., BitTorrent and
Metalink). In this case, there are some restrictions.
magnet URI, and followed by torrent download:
GID of BitTorrent meta data download is saved.
URI to torrent file, and followed by torrent download:
GID of torrent file download is saved.
URI to metalink file, and followed by file downloads described in metalink file:
GID of metalink file download is saved.
local torrent file:
GID of torrent download is saved.
local metalink file:
Any meaningful GID is not saved.
Returns:
str
"""
return self.get("save-session")
@save_session.setter
def save_session(self, value):
self.set("save-session", value)
@property
def save_session_interval(self):
"""
Save error/unfinished downloads to a file specified by --save-session option every SEC seconds.
If 0 is given, file will be saved only when aria2 exits. Default: 0.
Returns:
int
"""
return int(self.get("save-session-interval"))
@save_session_interval.setter
def save_session_interval(self, value):
self.set("save-session-interval", value)
@property
def socket_recv_buffer_size(self):
"""
Set the maximum socket receive buffer in bytes.
Specifying 0 will disable this option. This value will be set to socket file descriptor using SO_RCVBUF
socket option with setsockopt() call. Default: 0.
Returns:
int
"""
return int(self.get("socket-recv-buffer-size"))
@socket_recv_buffer_size.setter
def socket_recv_buffer_size(self, value):
self.set("socket-recv-buffer-size", value)
@property
def stop(self):
"""
Stop application after SEC seconds has passed.
If 0 is given, this feature is disabled. Default: 0.
Returns:
int
"""
return int(self.get("stop"))
@stop.setter
def stop(self, value):
self.set("stop", value)
@property
def stop_with_process(self):
"""
Stop application when process PID is not running.
This is useful if aria2 process is forked from a parent process. The parent process can fork aria2 with its
own pid and when parent process exits for some reason, aria2 can detect it and shutdown itself.
Returns:
int
"""
return int(self.get("stop-with-process"))
@stop_with_process.setter
def stop_with_process(self, value):
self.set("stop-with-process", value)
@property
def truncate_console_readout(self):
"""
Truncate console readout to fit in a single line.
Default: true.
Returns:
bool
"""
return bool_or_value(self.get("truncate-console-readout"))
@truncate_console_readout.setter
def truncate_console_readout(self, value):
self.set("truncate-console-readout", bool_to_str(value))
PK ! z aria2p/stats.py"""
This module defines the Stats class, which holds information retrieved with the ``get_global_stat`` method of the
client.
"""
from .utils import human_readable_bytes
class Stats:
"""This class holds information retrieved with the ``get_global_stat`` method of the client."""
def __init__(self, struct):
"""
Initialization method.
Args:
struct (dict): a dictionary Python object returned by the JSON-RPC client.
"""
self._struct = struct
@property
def download_speed(self):
"""Overall download speed (byte/sec)."""
return int(self._struct.get("downloadSpeed"))
def download_speed_string(self, human_readable=True):
if human_readable:
return human_readable_bytes(self.download_speed, delim=" ", postfix="/s")
return str(self.download_speed) + " B/s"
@property
def upload_speed(self):
"""Overall upload speed(byte/sec)."""
return int(self._struct.get("uploadSpeed"))
def upload_speed_string(self, human_readable=True):
if human_readable:
return human_readable_bytes(self.upload_speed, delim=" ", postfix="/s")
return str(self.upload_speed) + " B/s"
@property
def num_active(self):
"""The number of active downloads."""
return int(self._struct.get("numActive"))
@property
def num_waiting(self):
"""The number of waiting downloads."""
return int(self._struct.get("numWaiting"))
@property
def num_stopped(self):
"""
The number of stopped downloads in the current session. This value is capped by the --max-download-result
option.
"""
return int(self._struct.get("numStopped"))
@property
def num_stopped_total(self):
"""The number of stopped downloads in the current session and not capped by the --max-download-result option."""
return int(self._struct.get("numStoppedTotal"))
PK ! u[ aria2p/utils.py"""
Utils module.
This module contains simple utility functions.
"""
def human_readable_timedelta(value):
pieces = []
if value.days:
pieces.append(f"{value.days}d")
seconds = value.seconds
if seconds >= 3600:
hours = int(seconds / 3600)
pieces.append(f"{hours}h")
seconds -= hours * 3600
if seconds >= 60:
minutes = int(seconds / 60)
pieces.append(f"{minutes}m")
seconds -= minutes * 60
if seconds > 0 or not pieces:
pieces.append(f"{seconds}s")
return "".join(pieces)
def human_readable_bytes(value, digits=2, delim="", postfix=""):
unit = "B"
for u in ("KiB", "MiB", "GiB", "TiB"):
if value > 1000:
value /= 1024
unit = u
else:
break
return f"{value:.{digits}f}" + delim + unit + postfix
def bool_or_value(value):
if value == "true":
return True
elif value == "false":
return False
else:
return value
def bool_to_str(value):
if value is True:
return "true"
elif value is False:
return "false"
else:
return value
PK ! ᩰ pyproject.toml[build-system]
requires = ["poetry>=0.12"]
build-backend = "poetry.masonry.api"
[tool.poetry]
name = "aria2p"
version = "0.2.2"
description = "Command-line tool and library to interact with an aria2c daemon process with JSON-RPC."
license = "ISC"
authors = ["Timothée Mazzucotelli "]
readme = 'README.md'
repository = "https://github.com/pawamoy/aria2p"
homepage = "https://github.com/pawamoy/aria2p"
keywords = ['aria2', 'aria2c', 'aria2-cli']
packages = [ { include = "aria2p", from = "src" } ]
include = [
"README.md",
"pyproject.toml"
]
[tool.poetry.dependencies]
python = "^3.6"
requests = "*"
[tool.poetry.dev-dependencies]
bandit = "^1.5"
black = { version = "*", allows-prereleases = true }
flake8 = "^3.6"
ipython = "^7.2"
isort = "^4.3"
jinja2-cli = { git = "https://github.com/mattrobenolt/jinja2-cli.git" }
pytest = "^4.3"
pytest-cov = "^2.6"
pytest-sugar = "^0.9.2"
pytest-xdist = "^1.26"
recommonmark = "^0.4.0"
responses = "^0.10.5"
safety = "^1.8"
sphinx = "^1.8"
sphinxcontrib-spelling = "^4.2"
sphinx-rtd-theme = "^0.4.2"
toml = "^0.10.0"
[tool.poetry.scripts]
aria2p = 'aria2p.cli:main'
[tool.black]
line-length = 120
PK !HM' * ' aria2p-0.2.2.dist-info/entry_points.txtN+I/N.,()J,L4*Pz9Vy\\ PK ! 6{ aria2p-0.2.2.dist-info/LICENSEISC License
Copyright (c) 2018-2019, Timothée Mazzucotelli
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
PK !HnHT U aria2p-0.2.2.dist-info/WHEEL
A
н#Z;/"d&F[xzw@Zpy3Fv]\fi4WZ^EgM_-]#0(q7PK !H0 Q *1 aria2p-0.2.2.dist-info/METADATAZrFSW -oYr$%%HzrS,M6QL&>b;)R'Iըl ٷƹ]]2SA3кp#nRyw^u^8OU*
B3OAdQs
4==ΫmMI*U,$8C&*ȓlym]*/َe,kj&A*YU慺j5xxН(E.Ⱥ% Gۏَ(mB
e$G[ O[}I7Og,VgBv77-A]i
b_9<
tV;Ӣmy4$ټj/m[v_f!6^jrxEsƉpo^
-&倁@]9_KIETy`hx̀J̓e "%Y$Ⱦ]A+ƘXx
:,HIx?kߍ1 qe;s{?RDI9!L#hhsky'"w0n\+ahv(:.ѮXވ
~<#f)pep5{-:℈@rd<[a,Ůbrl90U 'Yg
NZ[DbbK-+q[b4`PdWcB
,s(iwI,<K-Raz
kW*1Cn1