Documentation
¶
Overview ¶
Package aria2g provides a client for aria2's JSON-RPC API over HTTP and WebSocket.
Index ¶
- Constants
- Variables
- type BatchResult
- type Bitfield
- type Bittorrent
- type BittorrentInfo
- type Client
- func (c *Client) AddMetalink(ctx context.Context, metalink string, options Options, position *int) ([]string, error)
- func (c *Client) AddTorrent(ctx context.Context, torrent string, uris []string, options Options, ...) (string, error)
- func (c *Client) AddURI(ctx context.Context, uris []string, options Options, position *int) (string, error)
- func (c *Client) Batch(ctx context.Context, calls []MethodCall) ([]BatchResult, error)
- func (c *Client) Call(ctx context.Context, method string, result any, params ...any) error
- func (c *Client) ChangeGlobalOption(ctx context.Context, options Options) error
- func (c *Client) ChangeOption(ctx context.Context, gid string, options Options) error
- func (c *Client) ChangePosition(ctx context.Context, gid string, pos int, how PositionMode) (int, error)
- func (c *Client) ChangeURI(ctx context.Context, gid string, fileIndex int, del, add []string, ...) ([2]int, error)
- func (c *Client) Close() error
- func (c *Client) Endpoint() string
- func (c *Client) ForcePause(ctx context.Context, gid string) (string, error)
- func (c *Client) ForcePauseAll(ctx context.Context) error
- func (c *Client) ForceRemove(ctx context.Context, gid string) (string, error)
- func (c *Client) ForceShutdown(ctx context.Context) error
- func (c *Client) GetFiles(ctx context.Context, gid string) ([]File, error)
- func (c *Client) GetGlobalOption(ctx context.Context) (Options, error)
- func (c *Client) GetGlobalStat(ctx context.Context) (GlobalStat, error)
- func (c *Client) GetOption(ctx context.Context, gid string) (Options, error)
- func (c *Client) GetPeers(ctx context.Context, gid string) ([]Peer, error)
- func (c *Client) GetPieceStat(ctx context.Context, gid string) (Bitfield, error)
- func (c *Client) GetServers(ctx context.Context, gid string) ([]Server, error)
- func (c *Client) GetSessionInfo(ctx context.Context) (SessionInfo, error)
- func (c *Client) GetURIs(ctx context.Context, gid string, fileIndex int) ([]URI, error)
- func (c *Client) GetVersion(ctx context.Context) (Version, error)
- func (c *Client) ListMethods(ctx context.Context) ([]string, error)
- func (c *Client) ListNotifications(ctx context.Context) ([]string, error)
- func (c *Client) MultiCall(ctx context.Context, calls []MethodCall) ([]json.RawMessage, error)
- func (c *Client) Notifications() <-chan Notification
- func (c *Client) Pause(ctx context.Context, gid string) (string, error)
- func (c *Client) PauseAll(ctx context.Context) error
- func (c *Client) PurgeDownloadResult(ctx context.Context) error
- func (c *Client) Remove(ctx context.Context, gid string) (string, error)
- func (c *Client) RemoveDownloadResult(ctx context.Context, gid string) (string, error)
- func (c *Client) SaveSession(ctx context.Context) error
- func (c *Client) Shutdown(ctx context.Context) error
- func (c *Client) TellActive(ctx context.Context, keys []string) ([]Download, error)
- func (c *Client) TellStatus(ctx context.Context, gid string, keys []string) (Download, error)
- func (c *Client) TellStopped(ctx context.Context, offset, num int, keys []string) ([]Download, error)
- func (c *Client) TellWaiting(ctx context.Context, offset, num int, keys []string) ([]Download, error)
- func (c *Client) Unpause(ctx context.Context, gid string) (string, error)
- func (c *Client) UnpauseAll(ctx context.Context) error
- type Config
- type Download
- type Event
- type File
- type GlobalStat
- type HTTPError
- type MethodCall
- type Notification
- type Options
- type Peer
- type PositionMode
- type RPCError
- type Server
- type ServerInfo
- type SessionInfo
- type URI
- type Version
Examples ¶
Constants ¶
const ( // DefaultEndpoint is the aria2 JSON-RPC endpoint used when Config.Endpoint // is empty. DefaultEndpoint = "http://localhost:6800/jsonrpc" // DefaultMaxResponseBytes is the default maximum size of one RPC response. DefaultMaxResponseBytes = int64(16 << 20) // DefaultNotificationBuffer is the default number of WebSocket // notifications that may wait for the application. DefaultNotificationBuffer = 64 )
const ( // NotificationDownloadStart is emitted when a download starts. NotificationDownloadStart = "aria2.onDownloadStart" // NotificationDownloadPause is emitted when a download is paused. NotificationDownloadPause = "aria2.onDownloadPause" // NotificationDownloadStop is emitted when a download is stopped by the user. NotificationDownloadStop = "aria2.onDownloadStop" // NotificationDownloadComplete is emitted when a download completes. NotificationDownloadComplete = "aria2.onDownloadComplete" // NotificationDownloadError is emitted when a download stops because of an error. NotificationDownloadError = "aria2.onDownloadError" // NotificationBTDownloadComplete is emitted when a BitTorrent download completes and seeding begins. NotificationBTDownloadComplete = "aria2.onBtDownloadComplete" )
Variables ¶
var ( // ErrResponseTooLarge indicates that an RPC response exceeded the configured MaxResponseBytes limit. ErrResponseTooLarge = errors.New("aria2g: response exceeds configured size limit") // ErrClientClosed indicates that an operation used a closed WebSocket client. ErrClientClosed = errors.New("aria2g: WebSocket client is closed") // ErrNotificationOverflow indicates that an application did not consume WebSocket notifications quickly enough. // The client is closed when this occurs so that notifications are never silently dropped. ErrNotificationOverflow = errors.New("aria2g: WebSocket notification buffer is full") )
Functions ¶
This section is empty.
Types ¶
type BatchResult ¶
type BatchResult struct {
// Result contains the raw successful result for decoding with Decode.
Result json.RawMessage
// Error contains the per-call RPC failure, if any.
Error *RPCError
}
BatchResult is one result from Batch. Exactly one of Result and Error is set.
func (BatchResult) Decode ¶
func (r BatchResult) Decode(dst any) error
Decode unmarshals a successful batch result into dst, which must be a non-nil pointer. If the call failed, Decode returns its RPCError.
type Bitfield ¶
type Bitfield struct {
Bitfield string `json:"bitfield"`
CompletedLength string `json:"completedLength"`
TotalLength string `json:"totalLength"`
}
Bitfield contains piece-completion information for a download.
type Bittorrent ¶
type Bittorrent struct {
AnnounceList [][]string `json:"announceList"`
Comment string `json:"comment"`
CreationDate int64 `json:"creationDate"`
Mode string `json:"mode"`
Info BittorrentInfo `json:"info"`
}
Bittorrent contains BitTorrent-specific download metadata.
type BittorrentInfo ¶
type BittorrentInfo struct {
Name string `json:"name"`
}
BittorrentInfo contains metadata from a torrent's info dictionary.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client communicates with one aria2 RPC server. It is safe for concurrent use. A Client created by DialWebSocket or DialWebSocketWithConfig must be closed when no longer needed.
func DialWebSocket ¶
DialWebSocket connects using aria2's WebSocket JSON-RPC transport. The returned Client supports all typed methods and delivers server notifications through Notifications.
Example ¶
package main
import (
"context"
"fmt"
"log"
"github.com/depthbomb/aria2g"
)
func main() {
ctx := context.Background()
client, err := aria2g.DialWebSocket(ctx, "http://localhost:6800", "rpc-secret")
if err != nil {
log.Fatal(err)
}
defer client.Close()
for notification := range client.Notifications() {
event, err := notification.DecodeEvent()
if err != nil {
log.Printf("invalid notification: %v", err)
continue
}
fmt.Printf("%s: %s\n", notification.Method, event.GID)
}
}
Output:
func DialWebSocketWithConfig ¶
DialWebSocketWithConfig connects using aria2's WebSocket JSON-RPC transport and the supplied configuration. The caller must close the returned Client.
func New ¶
New creates an HTTP client. endpoint may be a full JSON-RPC URL or an aria2 base URL.
Example ¶
package main
import (
"fmt"
"log"
"github.com/depthbomb/aria2g"
)
func main() {
client, err := aria2g.New("", "")
if err != nil {
log.Fatal(err)
}
fmt.Println(client.Endpoint())
}
Output: http://localhost:6800/jsonrpc
func NewWithConfig ¶
NewWithConfig creates an HTTP client using cfg. An empty endpoint selects DefaultEndpoint.
Example ¶
package main
import (
"fmt"
"log"
"time"
"github.com/depthbomb/aria2g"
)
func main() {
client, err := aria2g.NewWithConfig(aria2g.Config{
Endpoint: "https://downloads.example.com/aria2",
Secret: "rpc-secret",
Timeout: 30 * time.Second,
MaxResponseBytes: 4 << 20,
})
if err != nil {
log.Fatal(err)
}
fmt.Println(client.Endpoint())
}
Output: https://downloads.example.com/aria2/jsonrpc
func (*Client) AddMetalink ¶
func (c *Client) AddMetalink(ctx context.Context, metalink string, options Options, position *int) ([]string, error)
AddMetalink adds a base64-encoded Metalink document and returns its download GIDs. position is nil to append the resulting downloads to the queue.
func (*Client) AddTorrent ¶
func (c *Client) AddTorrent(ctx context.Context, torrent string, uris []string, options Options, position *int) (string, error)
AddTorrent adds a base64-encoded torrent file and returns its GID. uris optionally provides web-seed URIs; position is nil to append to the queue.
func (*Client) AddURI ¶
func (c *Client) AddURI(ctx context.Context, uris []string, options Options, position *int) (string, error)
AddURI adds a download from one or more source URIs and returns its GID. position is optional; nil appends the download to aria2's queue.
Example ¶
package main
import (
"context"
"fmt"
"log"
"github.com/depthbomb/aria2g"
)
func main() {
client, err := aria2g.New("http://localhost:6800", "rpc-secret")
if err != nil {
log.Fatal(err)
}
gid, err := client.AddURI(context.Background(), []string{
"https://example.com/archive.zip",
}, aria2g.Options{
"dir": "downloads",
"max-connection-per-server": "8",
}, nil)
if err != nil {
log.Fatal(err)
}
fmt.Println(gid)
}
Output:
func (*Client) Batch ¶
func (c *Client) Batch(ctx context.Context, calls []MethodCall) ([]BatchResult, error)
Batch sends native JSON-RPC batch requests in one HTTP request or WebSocket message. Results are returned in call order even if the server reorders them. Per-call RPC failures are stored in BatchResult.Error.
Example ¶
package main
import (
"context"
"fmt"
"log"
"github.com/depthbomb/aria2g"
)
func main() {
client, err := aria2g.New("http://localhost:6800", "rpc-secret")
if err != nil {
log.Fatal(err)
}
results, err := client.Batch(context.Background(), []aria2g.MethodCall{
{Method: "getVersion"},
{Method: "getGlobalStat"},
})
if err != nil {
log.Fatal(err)
}
var version aria2g.Version
if err := results[0].Decode(&version); err != nil {
log.Fatal(err)
}
fmt.Println(version.Version)
}
Output:
func (*Client) Call ¶
Call invokes a fully-qualified aria2 method (for example, "aria2.tellActive"). Unqualified names are prefixed with "aria2.". result must be a non-nil pointer. The secret token is inserted automatically.
Example ¶
package main
import (
"context"
"fmt"
"log"
"github.com/depthbomb/aria2g"
)
func main() {
client, err := aria2g.New("http://localhost:6800", "rpc-secret")
if err != nil {
log.Fatal(err)
}
// Call provides access to RPC methods that do not yet have a typed wrapper.
var methods []string
if err := client.Call(context.Background(), "system.listMethods", &methods); err != nil {
log.Fatal(err)
}
fmt.Println(methods)
}
Output:
func (*Client) ChangeGlobalOption ¶
ChangeGlobalOption updates aria2's changeable global options.
func (*Client) ChangeOption ¶
ChangeOption changes options for a download while it is active or waiting.
func (*Client) ChangePosition ¶
func (c *Client) ChangePosition(ctx context.Context, gid string, pos int, how PositionMode) (int, error)
ChangePosition moves a queued download and returns its new zero-based position. how must be one of aria2's position modes: POS_SET, POS_CUR, or POS_END.
func (*Client) ChangeURI ¶
func (c *Client) ChangeURI(ctx context.Context, gid string, fileIndex int, del, add []string, position *int) ([2]int, error)
ChangeURI removes and adds source URIs for a file. It returns removed and added counts. position is nil to use aria2's default insertion position.
func (*Client) ForcePause ¶
ForcePause immediately pauses a download and returns its GID.
func (*Client) ForcePauseAll ¶
ForcePauseAll immediately pauses every active download.
func (*Client) ForceRemove ¶
ForceRemove immediately removes a download and returns its GID.
func (*Client) ForceShutdown ¶
ForceShutdown immediately stops aria2, interrupting active downloads.
func (*Client) GetGlobalOption ¶
GetGlobalOption returns aria2's global options.
func (*Client) GetGlobalStat ¶
func (c *Client) GetGlobalStat(ctx context.Context) (GlobalStat, error)
GetGlobalStat returns aggregate transfer speeds and download counts.
func (*Client) GetPieceStat ¶
GetPieceStat returns piece-completion information using tellStatus. aria2 has no getPieceStat RPC method; this is a convenience operation retained for callers that only need the three piece-related fields.
func (*Client) GetServers ¶
GetServers returns per-file HTTP/FTP server information for a download.
func (*Client) GetSessionInfo ¶
func (c *Client) GetSessionInfo(ctx context.Context) (SessionInfo, error)
GetSessionInfo returns the current aria2 session identifier.
func (*Client) GetVersion ¶
GetVersion returns the aria2 version and enabled features.
func (*Client) ListMethods ¶
ListMethods returns the RPC methods advertised by aria2.
func (*Client) ListNotifications ¶
ListNotifications returns the notifications emitted by aria2.
func (*Client) MultiCall ¶
func (c *Client) MultiCall(ctx context.Context, calls []MethodCall) ([]json.RawMessage, error)
MultiCall invokes several methods through system.multicall in one request. Successful slots retain system.multicall's one-element array wrapper; sub-call errors are represented by aria2's fault object in their slot. Batch is usually more convenient because it separates per-call errors.
func (*Client) Notifications ¶
func (c *Client) Notifications() <-chan Notification
Notifications returns the notification stream for a WebSocket client. It returns nil for an HTTP client. The channel closes when the client closes.
func (*Client) PurgeDownloadResult ¶
PurgeDownloadResult removes all completed and errored download results.
func (*Client) RemoveDownloadResult ¶
RemoveDownloadResult removes one completed or errored result and returns its GID.
func (*Client) SaveSession ¶
SaveSession writes the current session to aria2's configured session file.
func (*Client) TellActive ¶
TellActive returns every active download. keys limits returned status fields.
func (*Client) TellStatus ¶
TellStatus returns status for gid. Pass nil or an empty keys slice for all fields.
func (*Client) TellStopped ¶
func (c *Client) TellStopped(ctx context.Context, offset, num int, keys []string) ([]Download, error)
TellStopped returns up to num stopped downloads beginning at offset. keys limits fields.
func (*Client) TellWaiting ¶
func (c *Client) TellWaiting(ctx context.Context, offset, num int, keys []string) ([]Download, error)
TellWaiting returns up to num queued downloads beginning at offset. keys limits fields.
type Config ¶
type Config struct {
// Endpoint is an aria2 base URL or full JSON-RPC URL. An empty value uses DefaultEndpoint. HTTP constructors accept
// http and https URLs; WebSocket constructors also accept ws and wss and convert HTTP schemes automatically.
Endpoint string
// Secret is aria2's RPC secret without the "token:" prefix. An empty value disables token authentication.
Secret string
// HTTPClient supplies the transport used for HTTP requests and WebSocket handshakes. A shallow copy is made before
// applying other Config fields. Nil uses http.DefaultClient.
HTTPClient *http.Client
// Timeout replaces HTTPClient.Timeout when nonzero. Per-call contexts can impose shorter deadlines. A negative
// value is invalid.
Timeout time.Duration
// TLSConfig configures TLS for HTTPS and WSS endpoints. It is cloned before use and requires HTTPClient.Transport
// to be nil or an *http.Transport.
TLSConfig *tls.Config
// MaxResponseBytes limits a single HTTP or WebSocket response. Zero uses DefaultMaxResponseBytes; a negative value
// is invalid.
MaxResponseBytes int64
// NotificationBuffer bounds notifications waiting for the application. If it fills, the WebSocket connection closes
// with ErrNotificationOverflow rather than dropping events or growing memory without bound. Zero uses
// DefaultNotificationBuffer.
NotificationBuffer int
}
Config controls a Client. HTTPClient is copied before Timeout is applied, so constructors never mutate a caller-owned client. A zero Timeout leaves the HTTP client's timeout unchanged. MaxResponseBytes defaults to 16 MiB.
type Download ¶
type Download struct {
GID string `json:"gid"`
Status string `json:"status"`
TotalLength string `json:"totalLength"`
CompletedLength string `json:"completedLength"`
UploadLength string `json:"uploadLength"`
Bitfield string `json:"bitfield"`
DownloadSpeed string `json:"downloadSpeed"`
UploadSpeed string `json:"uploadSpeed"`
InfoHash string `json:"infoHash"`
NumSeeders string `json:"numSeeders"`
Seeder string `json:"seeder"`
PieceLength string `json:"pieceLength"`
NumPieces string `json:"numPieces"`
Connections string `json:"connections"`
ErrorCode string `json:"errorCode"`
ErrorMessage string `json:"errorMessage"`
FollowedBy []string `json:"followedBy"`
Following string `json:"following"`
BelongsTo string `json:"belongsTo"`
Dir string `json:"dir"`
Files []File `json:"files"`
Bittorrent *Bittorrent `json:"bittorrent,omitempty"`
VerifiedLength string `json:"verifiedLength"`
VerifyIntegrityPending string `json:"verifyIntegrityPending"`
}
Download is a download status as returned by tellActive/tellWaiting/tellStopped.
type Event ¶
type Event struct {
GID string `json:"gid"`
}
Event identifies the download associated with an aria2 notification.
type File ¶
type File struct {
Index string `json:"index"`
Path string `json:"path"`
Length string `json:"length"`
CompletedLength string `json:"completedLength"`
Selected string `json:"selected"`
URIs []URI `json:"uris"`
}
File describes one file in a download and its source URIs.
type GlobalStat ¶
type GlobalStat struct {
DownloadSpeed string `json:"downloadSpeed"`
UploadSpeed string `json:"uploadSpeed"`
NumActive string `json:"numActive"`
NumWaiting string `json:"numWaiting"`
NumStopped string `json:"numStopped"`
NumStoppedTotal string `json:"numStoppedTotal"`
}
GlobalStat contains aria2's aggregate transfer speeds and download counts.
type HTTPError ¶
type HTTPError struct {
// StatusCode is the HTTP response status code.
StatusCode int
// Status is the complete HTTP response status, such as "503 Service Unavailable".
Status string
// Body contains the size-limited, whitespace-trimmed response body.
Body string
}
HTTPError reports a non-2xx response from the RPC endpoint.
type MethodCall ¶
type MethodCall struct {
// Method is a fully-qualified RPC method or an unqualified aria2 method.
Method string
// Params contains method parameters without the authentication token.
Params []any
}
MethodCall is one request for Batch or MultiCall. Params do not include the authentication token; it is added automatically to aria2.* methods.
type Notification ¶
type Notification struct {
Method string `json:"method"`
Params json.RawMessage `json:"params"`
}
Notification is an aria2 server-initiated WebSocket notification. Params is the raw JSON array supplied by aria2. DecodeEvent decodes its standard event.
func (Notification) DecodeEvent ¶
func (n Notification) DecodeEvent() (Event, error)
DecodeEvent decodes the single download event in n.Params.
Example ¶
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/depthbomb/aria2g"
)
func main() {
n := aria2g.Notification{
Method: aria2g.NotificationDownloadComplete,
Params: json.RawMessage(`[{"gid":"2089b05ecca3d829"}]`),
}
event, err := n.DecodeEvent()
if err != nil {
log.Fatal(err)
}
fmt.Println(event.GID)
}
Output: 2089b05ecca3d829
type Options ¶
Options are aria2 option key/value pairs. Values are normally strings. The header and index-out options may also be []string, as defined by aria2's RPC protocol.
type Peer ¶
type Peer struct {
PeerID string `json:"peerId"`
IP string `json:"ip"`
Port string `json:"port"`
Bitfield string `json:"bitfield"`
AmChoking string `json:"amChoking"`
PeerChoking string `json:"peerChoking"`
DownloadSpeed string `json:"downloadSpeed"`
UploadSpeed string `json:"uploadSpeed"`
Seeder string `json:"seeder"`
}
Peer describes a connected BitTorrent peer.
type PositionMode ¶
type PositionMode string
PositionMode controls how ChangePosition interprets its pos argument.
const ( // PositionSet moves a download to the absolute zero-based position pos. PositionSet PositionMode = "POS_SET" // PositionCurrent moves a download by pos positions relative to its current position. PositionCurrent PositionMode = "POS_CUR" // PositionEnd moves a download by pos positions relative to the end of the queue. PositionEnd PositionMode = "POS_END" )
type RPCError ¶
type RPCError struct {
// Code is aria2's JSON-RPC error code.
Code int `json:"code"`
// Message describes the RPC failure.
Message string `json:"message"`
// Data contains optional structured details supplied by aria2.
Data json.RawMessage `json:"data,omitempty"`
}
RPCError is an error returned by aria2.
type Server ¶
type Server struct {
Index string `json:"index"`
Servers []ServerInfo `json:"servers"`
}
Server groups the HTTP or FTP servers used for one file in a download.
type ServerInfo ¶
type ServerInfo struct {
URI string `json:"uri"`
CurrentURI string `json:"currentUri"`
DownloadSpeed string `json:"downloadSpeed"`
}
ServerInfo describes one HTTP or FTP source and its current transfer speed.
type SessionInfo ¶
type SessionInfo struct {
SessionID string `json:"sessionId"`
}
SessionInfo identifies the running aria2 session.
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
add-download
command
Program add-download submits a URI and follows it until it stops.
|
Program add-download submits a URI and follows it until it stops. |
|
batch
command
Program batch combines independent JSON-RPC calls into one request.
|
Program batch combines independent JSON-RPC calls into one request. |
|
concurrent-status
command
Program concurrent-status fetches several download statuses concurrently.
|
Program concurrent-status fetches several download statuses concurrently. |
|
version
command
Program version prints information about the aria2c daemon.
|
Program version prints information about the aria2c daemon. |
|
websocket
command
Program websocket prints aria2 download events until interrupted.
|
Program websocket prints aria2 download events until interrupted. |