arigo

package module
v0.0.0-...-8732249 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2022 License: MIT Imports: 14 Imported by: 0

README

arigo

Build Status Go Report Card Documentation

A client library for the aria2 RPC interface.

Features:

  • Complete implementation of all supported methods.
  • Bidirectional communication over WebSocket which makes it possible to receive events and know when a download has completed.

arigo currently doesn't start and manage the aria2c process for you. To start aria2 use the following command:

aria2c --enable-rpc --rpc-listen-all

If aria2 is not installed then head on to https://aria2.github.io/ and follow the instructions there.

Example

package main

import (
	"fmt"
	"codeberg.org/qwert0p/arigo"
)

func main() {
	c, err := arigo.Dial("ws://localhost:6800/jsonrpc", "")
	if err != nil {
		panic(err)
	}
	
	// Download is a utility method which calls AddURI and 
	// then waits for the download to complete
	status, err := c.Download(arigo.URIs("https://example.org/file"), nil)
	if err != nil {
		panic(err)
	}
	
	// download complete
	fmt.Println(status.GID)
}

Documentation

Overview

Package arigo is a library to communicate with the aria2 RPC interface.

About aria2

aria2 is a utility for downloading files. The supported protocols are HTTP(S), FTP, SFTP, BitTorrent, and Metalink. aria2 can download a file from multiple sources/protocols and tries to utilize your maximum download bandwidth. It supports downloading a file from HTTP(S)/FTP /SFTP and BitTorrent at the same time, while the data downloaded from HTTP(S)/FTP/SFTP is uploaded to the BitTorrent swarm. Using Metalink chunk checksums, aria2 automatically validates chunks of data while downloading a file.

You can read more about aria2 here: https://aria2.github.io/

Index

Examples

Constants

View Source
const (
	// QueueEndPosition represents the end of the download queue.
	QueueEndPosition = ^uint(0)
)

Variables

View Source
var (
	// ErrDownloadError represents an error that occurred during the download
	ErrDownloadError = errors.New("download encountered error")
	// ErrDownloadStopped is the error returned when a download is stopped
	ErrDownloadStopped = errors.New("download stopped")
)

Functions

func URIs

func URIs(uris ...string) []string

URIs creates a string slice from the given uris. This is a convenience function for the various client methods that accept a slice of URIs (strings).

Types

type BitTorrentStatus

type BitTorrentStatus struct {
	// List of lists of announce URIs.
	// If the torrent contains announce and no announce-list,
	// announce is converted to the announce-list format
	AnnounceList []URI                `json:"announceList"`
	Comment      string               `json:"comment"`             // The comment of the torrent
	CreationDate UNIXTime             `json:"creationDate,string"` // The creation time of the torrent
	Mode         TorrentMode          `json:"mode"`                // File mode of the torrent
	Info         BitTorrentStatusInfo `json:"info"`                // Information from the info dictionary
}

BitTorrentStatus holds information for a BitTorrent download

type BitTorrentStatusInfo

type BitTorrentStatusInfo struct {
	Name string `json:"name"` // name in info dictionary
}

A BitTorrentStatusInfo holds information from the info dictionary.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client represents a connection to an aria2 rpc interface over websocket.

Example

Dial is a convenience method which connects to an aria2 RPC interface. It establishes a WebSocket connection to the given url and passes it to the NewClient() method. The client is also started.

// arigo uses a WebSocket connection to communicate with the aria2 RPC.
// This makes it possible to receive download events.
// authToken is the secret string set on the aria2 server. Setting it to an empty string
// indicates that no password should be used.
client, err := Dial("ws://localhost:6800/jsonrpc", "")

// err is returned if no connection to the RPC interface could be established.
if err != nil {
	panic(err)
}

// client is now connected and can be used
gid, err := client.AddURI(URIs("https://example.org/file"), nil)
if err != nil {
	panic(err)
}

// gid isn't just a string but a GID instance.
// this makes it possible to use all the client methods you would normally
// pass a gid to directly on the GID instance.
// WaitForDownload() is a special method which waits for the download to complete
// (using the aria2 events)
if err = gid.WaitForDownload(); err != nil {
	panic(err)
}

// Get the status of the now completed download.
// The TellStatus() method accepts the keys of the Status struct
// which are to be requested. Please note that the keys must match
// the aria2 keys, which may differ from the keys used in the golang
// representation.
// For the aria2 status documentation see: https://aria2.github.io/manual/en/html/aria2c.html#aria2.tellStatus
status, err := gid.TellStatus("status")
if err != nil {
	panic(err)
}

fmt.Println(status.Status)
Output:

func Dial

func Dial(url string, authToken string) (client *Client, err error)

Dial creates a new connection to an aria2 rpc interface. It returns a new client.

func DialContext

func DialContext(ctx context.Context, url string, authToken string) (client *Client, err error)

DialContext creates a new connection to an aria2 rpc interface. It returns a new client.

func NewClient

func NewClient(rpcClient *rpc2.Client, authToken string) *Client

NewClient creates a new client. The client needs to be manually ran using the Run method.

func (c *Client) AddMetalink(metalink []byte, options *Options) ([]GID, error)

AddMetalink adds a Metalink download by uploading a “.metalink” file. metalink is the contents of the “.metalink” file.

The new download is appended to the end of the queue.

This method returns an array of GIDs of newly registered downloads.

func (*Client) AddMetalinkAtPosition

func (c *Client) AddMetalinkAtPosition(metalink []byte, position uint, options *Options) ([]GID, error)

AddMetalinkAtPosition adds a Metalink download at a specific position in the queue by uploading a “.metalink” file. metalink is the contents of the “.metalink” file.

The new download will be inserted at position in the waiting queue. If position is nil 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.

func (*Client) AddTorrent

func (c *Client) AddTorrent(torrent []byte, uris []string, options *Options) (GID, error)

AddTorrent adds a BitTorrent download by uploading a “.torrent” file. If you want to add a BitTorrent Magnet URI, use the AddURI() method instead. torrent must be 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.

The new download is appended to the end of the queue.

This method returns the GID of the newly registered download.

func (*Client) AddTorrentAtPosition

func (c *Client) AddTorrentAtPosition(torrent []byte, uris []string, position uint, options *Options) (GID, error)

AddTorrentAtPosition adds a BitTorrent download at a specific position in the queue. If you want to add a BitTorrent Magnet URI, use the AddURI() method instead. torrent must be 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.

The new download will be inserted at position in the waiting queue. If position is nil 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.

func (*Client) AddURI

func (c *Client) AddURI(uris []string, options *Options) (GID, error)

AddURI adds a new download. uris is a slice 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.

The new download is appended to the end of the queue.

This method returns the GID of the newly registered download.

func (*Client) AddURIAtPosition

func (c *Client) AddURIAtPosition(uris []string, position uint, options *Options) (GID, error)

AddURIAtPosition adds a new download at a specific position in the queue. uris is a slice of HTTP/FTP/SFTP/BitTorrent URIs 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.

The new download will be inserted at position in the waiting queue. If position is nil 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.

func (*Client) ChangeGlobalOptions

func (c *Client) ChangeGlobalOptions(options Options) error

ChangeGlobalOptions changes global options dynamically.

The following global options are available:

  • BtMaxOpenFiles
  • DownloadResult
  • KeepUnfinishedDownloadResult
  • Log
  • LogLevel
  • MaxConcurrentDownloads
  • MaxDownloadResult
  • MaxOverallDownloadLimit
  • MaxOverallUploadLimit
  • OptimizeConcurrentDownloads
  • SaveCookies
  • SaveSession
  • ServerStatOf

Except for the following options, all other Options are available as well:

  • Checksum
  • IndexOut
  • Out
  • Pause
  • SelectFile

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.

func (*Client) ChangeOptions

func (c *Client) ChangeOptions(gid string, options Options) error

ChangeOptions changes options of the download denoted by gid dynamically.

Except for following options, all options are available:

  • DryRun
  • MetalinkBaseURI
  • ParameterizedURI
  • Pause
  • PieceLength
  • RPCSaveUploadMetadata

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):

  • BtMaxPeers
  • BtRequestPeerSpeedLimit
  • BtRemoveUnselectedFile
  • ForceSave
  • MaxDownloadLimit
  • MaxUploadLimit

func (*Client) ChangePosition

func (c *Client) ChangePosition(gid string, pos int, how PositionSetBehaviour) (int, error)

ChangePosition changes the position of the download denoted by gid in the queue.

If how is SetPositionStart, it moves the download to a position relative to the beginning of the queue. If how is SetPositionRelative, it moves the download to a position relative to the current position. If how is SetPositionEnd, 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.

func (*Client) ChangeURI

func (c *Client) ChangeURI(gid string, fileIndex uint, delURIs []string, addURIs []string) (uint, uint, error)

ChangeURI removes the URIs in delUris from and appends the URIs in addUris to download denoted by gid. 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. 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.

Returns two integers. The first integer is the number of URIs deleted. The second integer is the number of URIs added.

func (*Client) ChangeURIAt

func (c *Client) ChangeURIAt(gid string, fileIndex uint, delURIs []string, addURIs []string, position uint) (uint, uint, error)

ChangeURIAt removes the URIs in delUris from and appends the URIs in addUris to download denoted by gid. 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.

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.

Returns two integers. The first integer is the number of URIs deleted. The second integer is the number of URIs added.

func (*Client) Close

func (c *Client) Close() error

Close closes the connection to the aria2 rpc interface. The client becomes unusable after that point.

func (*Client) Delete

func (c *Client) Delete(gid string) (err error)

Delete removes the download denoted by gid and deletes all corresponding files. This is not an aria2 method.

func (*Client) Download

func (c *Client) Download(uris []string, options *Options) (status Status, err error)

Download adds a new download and waits for it to complete. It returns the status of the finished download.

func (*Client) DownloadWithContext

func (c *Client) DownloadWithContext(ctx context.Context, uris []string, options *Options) (status Status, err error)

DownloadWithContext adds a new download and waits for it to complete. The passed context can be used to cancel the download. It returns the status of the finished download.

func (*Client) ForcePause

func (c *Client) ForcePause(gid string) error

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

func (*Client) ForcePauseAll

func (c *Client) ForcePauseAll() error

ForcePauseAll is equal to calling ForcePause() for every active/waiting download.

func (*Client) ForceRemove

func (c *Client) ForceRemove(gid string) error

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

func (*Client) ForceShutdown

func (c *Client) ForceShutdown() error

ForceShutdown shuts down aria2. Behaves like the Shutdown() method but doesn't perform any actions which take time, such as contacting BitTorrent trackers to unregister downloads first.

func (*Client) GetFiles

func (c *Client) GetFiles(gid string) ([]File, error)

GetFiles returns the file list of the download denoted by gid. The response is a slice of Files.

func (*Client) GetGID

func (c *Client) GetGID(gid string) GID

GetGID creates a GID struct which you can use to interact with the download directly

func (*Client) GetGlobalOptions

func (c *Client) GetGlobalOptions() (Options, error)

GetGlobalOptions returns the global options. Note that this method does not return options which have no default value and have not been set on the command-line, in configuration files or RPC methods.

Because global options are used as a template for the options of newly added downloads, the response contains keys returned by the GetOption() method.

func (*Client) GetGlobalStats

func (c *Client) GetGlobalStats() (Stats, error)

GetGlobalStats returns global statistics such as the overall download and upload speeds.

func (*Client) GetOptions

func (c *Client) GetOptions(gid string) (Options, error)

GetOptions returns Options of the download denoted by gid. 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.

func (*Client) GetPeers

func (c *Client) GetPeers(gid string) ([]Peer, error)

GetPeers returns a list of peers of the download denoted by gid. This method is for BitTorrent only. The response is a slice of Peers.

func (*Client) GetServers

func (c *Client) GetServers(gid string) ([]FileServers, error)

GetServers returns currently connected HTTP(S)/FTP/SFTP servers of the download denoted by gid. Returns a slice of FileServers.

func (*Client) GetSessionInfo

func (c *Client) GetSessionInfo() (SessionInfo, error)

GetSessionInfo returns session information.

func (*Client) GetURIs

func (c *Client) GetURIs(gid string) ([]URI, error)

GetURIs returns the URIs used in the download denoted by gid. The response is a slice of URIs.

func (*Client) GetVersion

func (c *Client) GetVersion() (VersionInfo, error)

GetVersion returns the version of aria2 and the list of enabled features.

func (*Client) MultiCall

func (c *Client) MultiCall(methods ...*MethodCall) ([]MethodResult, error)

MultiCall executes multiple method calls in one request. Returns a MethodResult for each MethodCall in order.

func (*Client) Pause

func (c *Client) Pause(gid string) error

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

func (*Client) PauseAll

func (c *Client) PauseAll() error

PauseAll is equal to calling Pause() for every active/waiting download.

func (*Client) PurgeDownloadResults

func (c *Client) PurgeDownloadResults() error

PurgeDownloadResults purges completed/error/removed downloads to free memory

func (*Client) Remove

func (c *Client) Remove(gid string) error

Remove removes the download denoted by gid. If the specified download is in progress, it is first stopped. The status of the removed download becomes removed.

func (*Client) RemoveDownloadResult

func (c *Client) RemoveDownloadResult(gid string) error

RemoveDownloadResult removes a completed/error/removed download denoted by gid from memory.

func (*Client) Run

func (c *Client) Run()

Run runs the underlying rpcClient. There's no need to call this if the client was created using the Dial function.

func (*Client) SaveSession

func (c *Client) SaveSession() error

SaveSession saves the current session to a file specified by the SaveSession option.

func (*Client) Shutdown

func (c *Client) Shutdown() error

Shutdown shuts down aria2.

func (*Client) Subscribe

func (c *Client) Subscribe(evtType EventType, listener EventListener) UnsubscribeFunc

Subscribe registers the given listener for an event. The listener will be called every time the event occurs.

func (*Client) TellActive

func (c *Client) TellActive(keys ...string) ([]Status, error)

TellActive returns a slice of active downloads represented by their Status. keys does the same as in the TellStatus() method.

func (*Client) TellStatus

func (c *Client) TellStatus(gid string, keys ...string) (Status, error)

TellStatus returns the progress of the download denoted by gid.

If specified, the returned Status only contains the keys passed to the method. This is useful when you just want specific keys and avoid unnecessary transfers.

func (*Client) TellStopped

func (c *Client) TellStopped(offset int, num uint, keys ...string) ([]Status, error)

TellStopped returns a slice of stopped downloads represented by their Status.

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.

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 to the download before the last download, and so on. The returned statuses are in reversed order then.

If specified, the returned Statuses only contain the keys passed to the method.

func (*Client) TellWaiting

func (c *Client) TellWaiting(offset int, num uint, keys ...string) ([]Status, error)

TellWaiting returns a slice of waiting downloads including paused ones represented by their Status.

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.

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 to the download before the last download, and so on. The returned statuses are in reversed order then.

If specified, the returned Statuses only contain the keys passed to the method.

func (*Client) Unpause

func (c *Client) Unpause(gid string) error

Unpause changes the status of the download denoted by gid from paused to waiting, making the download eligible to be restarted.

func (*Client) UnpauseAll

func (c *Client) UnpauseAll() error

UnpauseAll is equal to calling Unpause() for every paused download.

func (*Client) WaitForDownload

func (c *Client) WaitForDownload(gid string) error

WaitForDownload waits for a download denoted by its gid to finish.

type DownloadEvent

type DownloadEvent struct {
	GID string
}

DownloadEvent represents the event emitted by aria2 concerning downloads. It only contains the gid of the download.

func (*DownloadEvent) String

func (e *DownloadEvent) String() string

type DownloadStatus

type DownloadStatus string

DownloadStatus represents the status of a download.

const (
	// StatusActive represents currently downloading/seeding downloads
	StatusActive DownloadStatus = "active"
	// StatusWaiting represents downloads in the queue
	StatusWaiting DownloadStatus = "waiting"
	// StatusPaused represents paused downloads
	StatusPaused DownloadStatus = "paused"
	// StatusError represents downloads that were stopped because of error
	StatusError DownloadStatus = "error"
	// StatusCompleted represents stopped and completed downloads
	StatusCompleted DownloadStatus = "completed"
	// StatusRemoved represents the downloads removed by user
	StatusRemoved DownloadStatus = "removed"
)

type EventDispatcher

type EventDispatcher interface {
	Dispatch(evtType EventType, event *DownloadEvent)
}

EventDispatcher is an interface capable of dispatching events.

type EventListener

type EventListener func(event *DownloadEvent)

EventListener represents a function which should be called when an event occurs.

type EventSubscriber

type EventSubscriber interface {
	Subscribe(evtType EventType, listener EventListener) UnsubscribeFunc
}

EventSubscriber is an interface which can be subscribed to.

type EventType

type EventType uint

EventType represents a DownloadEvent which can be subscribed to on the Client.

const (
	// StartEvent is dispatched when a download is started
	StartEvent EventType = iota
	// PauseEvent is dispatched when a download is paused
	PauseEvent
	// StopEvent is dispatched when a download is stopped
	StopEvent
	// CompleteEvent is dispatched when a download is completed
	CompleteEvent
	// BTCompleteEvent is dispatched when a BitTorrent download is completed
	BTCompleteEvent
	// ErrorEvent is dispatched when an error occurs
	ErrorEvent
)

func (EventType) String

func (i EventType) String() string

type ExitStatus

type ExitStatus uint8

ExitStatus is an integer returned by aria2 for downloads which describes why a download exited. Please see https://aria2.github.io/manual/en/html/aria2c.html#exit-status

const (
	// Success indicates that all downloads were successful.
	Success ExitStatus = iota

	// UnknownError indicates that an unknown error occurred.
	UnknownError

	// Timeout indicates that a timeout occurred.
	Timeout

	// ResourceNotFound indicates that a resource was not found.
	ResourceNotFound

	// ResourceNotFoundReached indicates that aria2 saw the specified number of “resource not found” error.
	// See the --max-file-not-found option.
	ResourceNotFoundReached

	// DownloadSpeedTooSlow indicates that a download aborted because download speed was too slow.
	// See --lowest-speed-limit option.
	DownloadSpeedTooSlow

	// NetworkError indicates that a network problem occurred.
	NetworkError

	// UnfinishedDownloads indicates that there were unfinished downloads.
	// This error is only reported if all finished downloads were successful and there were unfinished
	// downloads in a queue when aria2 exited by pressing Ctrl-C by an user or sending TERM or INT signal.
	UnfinishedDownloads

	// RemoteNoResume indicates that the remote server did not support resume when resume was required to complete download.
	RemoteNoResume

	// NotEnoughDiskSpace indicates that there was not enough disk space available.
	NotEnoughDiskSpace

	// PieceLengthMismatch indicates that the piece length was different from one in .aria2 control file.
	// See --allow-piece-length-change option.
	PieceLengthMismatch

	// SameFileBeingDownloaded indicates that aria2 was downloading same file at that moment.
	SameFileBeingDownloaded

	// SameInfoHashBeingDownloaded indicates that aria2 was downloading same info hash torrent at that moment.
	SameInfoHashBeingDownloaded

	// FileAlreadyExists indicates that the file already existed. See --allow-overwrite option.
	FileAlreadyExists

	//RenamingFailed indicates that renaming the file failed. See --auto-file-renaming option.
	RenamingFailed

	// CouldNotOpenExistingFile indicates that aria2 could not open existing file.
	CouldNotOpenExistingFile

	// CouldNotCreateNewFile indicates that aria2 could not create new file or truncate existing file.
	CouldNotCreateNewFile

	// FileIOError indicates that a file I/O error occurred.
	FileIOError

	// CouldNotCreateDirectory indicates that aria2 could not create directory.
	CouldNotCreateDirectory

	// NameResolutionFailed indicates that the name resolution failed.
	NameResolutionFailed

	// MetalinkParsingFailed indicates that aria2 could not parse Metalink document.
	MetalinkParsingFailed

	// FTPCommandFailed indicates that the FTP command failed.
	FTPCommandFailed

	// HTTPResponseHeaderBad indicates that the HTTP response header was bad or unexpected.
	HTTPResponseHeaderBad

	// TooManyRedirects indicates that too many redirects occurred.
	TooManyRedirects

	// HTTPAuthorizationFailed indicates that HTTP authorization failed.
	HTTPAuthorizationFailed

	// BencodedFileParseError indicates that aria2 could not parse bencoded file (usually “.torrent” file).
	BencodedFileParseError

	// TorrentFileCorrupt indicates that the “.torrent” file was corrupted or missing information that aria2 needed.
	TorrentFileCorrupt

	// MagnetURIBad indicates that the magnet URI was bad.
	MagnetURIBad

	// RemoteServerHandleRequestError indicates that the remote server was unable to handle the request due to a
	// temporary overloading or maintenance.
	RemoteServerHandleRequestError

	// JSONRPCParseError indicates that aria2 could not parse JSON-RPC request.
	JSONRPCParseError

	// Reserved is a reserved value. If you get this exit status then the library is probably out-of-date,
	// or the universe is breaking down.
	Reserved

	// ChecksumValidationFailed indicates that the checksum validation failed.
	ChecksumValidationFailed
)

func (ExitStatus) String

func (i ExitStatus) String() string

type File

type File struct {
	// Index of the file, starting at 1, in the same order as files appear in the multi-file torrent.
	Index  int    `json:"index,string"`
	Path   string `json:"path"`          // File path
	Length uint   `json:"length,string"` // File size in bytes

	// 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 TellStatus() method. This is because completedLength in GetFiles() only includes completed pieces.
	// On the other hand, completedLength in TellStatus() also includes partially completed pieces.
	CompletedLength uint `json:"completedLength,string"`

	// true if this file is selected by the SelectFile option.
	// If SelectFile is not specified or this is single-file torrent or not a torrent download at all,
	// this value is always true. Otherwise false.
	Selected bool  `json:"selected,string"`
	URIs     []URI `json:"uris"` // Array of URIs for this file.
}

File represents a single file downloaded by aria2. It is returned by the GetFiles() method.

type FileServers

type FileServers struct {
	// Index of the file, starting at 1,
	// in the same order as files appear in the multi-file metalink.
	Index   uint     `json:"index,string"`
	Servers []Server `json:"servers"` // Slice of Servers which are used for the file
}

FileServers holds the servers of a file

type GID

type GID struct {
	GID string // gid of the download
	// contains filtered or unexported fields
}

GID provides an object oriented approach to arigo. Instead of calling the methods on the client directly, you can call them on the GID instance.

func (*GID) ChangeOptions

func (gid *GID) ChangeOptions(changes Options) error

ChangeOptions changes options of the download denoted by gid dynamically.

Except for following options, all options are available:

  • DryRun
  • MetalinkBaseURI
  • ParameterizedURI
  • Pause
  • PieceLength
  • RPCSaveUploadMetadata

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):

  • BtMaxPeers
  • BtRequestPeerSpeedLimit
  • BtRemoveUnselectedFile
  • ForceSave
  • MaxDownloadLimit
  • MaxUploadLimit

func (*GID) ChangePosition

func (gid *GID) ChangePosition(pos int, how PositionSetBehaviour) (int, error)

ChangePosition changes the position of the download denoted by gid in the queue.

If how is SetPositionStart, it moves the download to a position relative to the beginning of the queue. If how is SetPositionRelative, it moves the download to a position relative to the current position. If how is SetPositionEnd, 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.

func (*GID) ChangeURI

func (gid *GID) ChangeURI(fileIndex uint, delURIs []string, addURIs []string) (uint, uint, error)

ChangeURI removes the URIs in delUris from and appends the URIs in addUris to download denoted by gid. 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. 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.

Returns two integers. The first integer is the number of URIs deleted. The second integer is the number of URIs added.

func (*GID) ChangeURIAt

func (gid *GID) ChangeURIAt(fileIndex uint, delURIs []string, addURIs []string, position uint) (uint, uint, error)

ChangeURIAt removes the URIs in delUris from and appends the URIs in addUris to download denoted by gid. 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 nil, 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.

Returns two integers. The first integer is the number of URIs deleted. The second integer is the number of URIs added.

func (*GID) Delete

func (gid *GID) Delete() error

Delete removes the download from disk as well as from aria2.

func (*GID) ForcePause

func (gid *GID) ForcePause() error

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

func (*GID) ForceRemove

func (gid *GID) ForceRemove() error

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

func (*GID) GetFiles

func (gid *GID) GetFiles() ([]File, error)

GetFiles returns the file list of the download. The response is a slice of File.

func (*GID) GetOptions

func (gid *GID) GetOptions() (Options, error)

GetOptions returns Options of the download denoted by gid. 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.

func (*GID) GetPeers

func (gid *GID) GetPeers() ([]Peer, error)

GetPeers returns a list of peers of the download denoted by gid. This method is for BitTorrent only. The response is a slice of Peers.

func (*GID) GetServers

func (gid *GID) GetServers() ([]FileServers, error)

GetServers returns currently connected HTTP(S)/FTP/SFTP servers of the download denoted by gid. Returns a slice of FileServers.

func (*GID) GetURIs

func (gid *GID) GetURIs() ([]URI, error)

GetURIs returns the URIs used in the download. The response is a slice of URI.

func (*GID) Pause

func (gid *GID) Pause() error

Pause pauses the download. The status of paused download becomes paused. If the download was active, the download is placed in the front of the queue. While the status is paused, the download is not started. To change status to waiting, use the Unpause() method.

func (*GID) Remove

func (gid *GID) Remove() error

Remove removes the download. If the specified download is in progress, it is first stopped. The status of the removed download becomes removed.

func (*GID) RemoveDownloadResult

func (gid *GID) RemoveDownloadResult() error

RemoveDownloadResult removes a completed/error/removed download denoted by gid from memory.

func (*GID) String

func (gid *GID) String() string

func (*GID) Subscribe

func (gid *GID) Subscribe(evtType EventType, listener EventListener) UnsubscribeFunc

Subscribe subscribes to the given event but only dispatches events concerning this GID.

func (*GID) TellStatus

func (gid *GID) TellStatus(keys ...string) (Status, error)

TellStatus returns the progress of the download. If specified, the response only contains only the keys passed to the method. If keys is empty, the response contains all keys. This is useful when you just want specific keys and avoid unnecessary transfers.

func (*GID) Unpause

func (gid *GID) Unpause() error

Unpause changes the status of the download from paused to waiting, making the download eligible to be restarted.

func (*GID) WaitForDownload

func (gid *GID) WaitForDownload() error

WaitForDownload waits for the download to finish.

type MethodCall

type MethodCall struct {
	MethodName string        `json:"methodName"` // Method name to call
	Params     []interface{} `json:"params"`     // Parameters to pass to the method
}

MethodCall represents a method call in a multi call operation

func NewMethodCall

func NewMethodCall(methodName string, params ...interface{}) *MethodCall

NewMethodCall creates a new MethodCall

type MethodCallError

type MethodCallError struct {
	Code    uint   `json:"code,string"`
	Message string `json:"message"`
}

MethodCallError represents an error returned by aria2 for a MethodCall

func (*MethodCallError) Error

func (e *MethodCallError) Error() string

type MethodResult

type MethodResult struct {
	Result []byte // Raw JSON value returned

	// Error encountered during the method call.
	// This is likely to be a MethodCallError but it's
	// not guaranteed.
	Error error
}

MethodResult represents the result of a MethodCall in a MultiCall operation.

func (*MethodResult) Unmarshal

func (res *MethodResult) Unmarshal(v interface{}) error

Unmarshal unmarshals the raw result into v. If the result contains an error, it is returned directly without ever even attempting to unmarshal the result.

type Options

type Options struct {
	AllProxy                      string   `json:"all-proxy,omitempty"`
	AllProxyPassword              string   `json:"all-proxy-passwd,omitempty"`
	AllProxyUser                  string   `json:"all-proxy-user,omitempty"`
	AllowOverwrite                bool     `json:"allow-overwrite,omitempty,string"`
	AllowPieceLengthChange        bool     `json:"allow-piece-length-change,omitempty,string"`
	AlwaysResume                  bool     `json:"always-resume,omitempty,string"`
	AsyncDNS                      bool     `json:"async-dns,omitempty,string"`
	AutoFileRenaming              bool     `json:"auto-file-renaming,omitempty,string"`
	BTEnableHookAfterHashCheck    bool     `json:"bt-enable-hook-after-hash-check,omitempty,string"`
	BTEnableLpd                   bool     `json:"bt-enable-lpd,omitempty,string"`
	BTExcludeTracker              string   `json:"bt-exclude-tracker,omitempty"`
	BTExternalIP                  string   `json:"bt-external-ip,omitempty"`
	BTForceEncryption             bool     `json:"bt-force-encryption,omitempty,string"`
	BTHashCheckSeed               bool     `json:"bt-hash-check-seed,omitempty,string"`
	BTLoadSavedMetadata           bool     `json:"bt-load-saved-metadata,omitempty,string"`
	BTMaxPeers                    uint     `json:"bt-max-peers,omitempty,string"`
	BTMetadataOnly                bool     `json:"bt-metadata-only,omitempty,string"`
	BTMinCryptoLevel              string   `json:"bt-min-crypto-level,omitempty"`
	BTPrioritizePiece             string   `json:"bt-prioritize-piece,omitempty"`
	BTRemoveUnselectedFile        bool     `json:"bt-remove-unselected-file,omitempty,string"`
	BTRequestPeerSpeedLimit       string   `json:"bt-request-peer-speed-limit,omitempty"`
	BTRequireCrypto               bool     `json:"bt-require-crypto,omitempty,string"`
	BTSaveMetadata                bool     `json:"bt-save-metadata,omitempty,string"`
	BTSeedUnverified              bool     `json:"bt-seed-unverified,omitempty,string"`
	BTStopTimeout                 uint     `json:"bt-stop-timeout,omitempty,string"`
	BTTracker                     string   `json:"bt-tracker,omitempty"`
	BTTrackerConnectTimeout       uint     `json:"bt-tracker-connect-timeout,omitempty,string"`
	BTTrackerInterval             uint     `json:"bt-tracker-interval,omitempty,string"`
	BTTrackerTimeout              uint     `json:"bt-tracker-timeout,omitempty,string"`
	CheckIntegrity                bool     `json:"check-integrity,omitempty,string"`
	Checksum                      string   `json:"checksum,omitempty"`
	ConditionalGet                bool     `json:"conditional-get,omitempty,string"`
	ConnectTimeout                uint     `json:"connect-timeout,omitempty,string"`
	ContentDispositionDefaultUTF8 bool     `json:"content-disposition-default-utf8,omitempty,string"`
	Continue                      bool     `json:"continue,omitempty,string"`
	Dir                           string   `json:"dir,omitempty"`
	DryRun                        bool     `json:"dry-run,omitempty,string"`
	EnableHTTPKeepAlive           bool     `json:"enable-http-keep-alive,omitempty,string"`
	EnableHTTPPipelining          bool     `json:"enable-http-pipelining,omitempty,string"`
	EnableMMap                    bool     `json:"enable-mmap,omitempty,string"`
	EnablePeerExchange            bool     `json:"enable-peer-exchange,omitempty,string"`
	FileAllocation                string   `json:"file-allocation,omitempty"`
	FollowMetalink                bool     `json:"follow-metalink,omitempty,string"`
	FollowTorrent                 bool     `json:"follow-torrent,omitempty,string"`
	ForceSave                     bool     `json:"force-save,omitempty,string"`
	FTPPasswd                     string   `json:"ftp-passwd,omitempty"`
	FTPPasv                       bool     `json:"ftp-pasv,omitempty,string"`
	FTPProxy                      string   `json:"ftp-proxy,omitempty"`
	FTPProxyPasswd                string   `json:"ftp-proxy-passwd,omitempty"`
	FTPProxyUser                  string   `json:"ftp-proxy-user,omitempty"`
	FTPReuseConnection            bool     `json:"ftp-reuse-connection,omitempty,string"`
	FTPType                       string   `json:"ftp-type,omitempty"`
	FTPUser                       string   `json:"ftp-user,omitempty"`
	GID                           string   `json:"gid,omitempty"`
	HashCheckOnly                 bool     `json:"hash-check-only,omitempty,string"`
	Headers                       []string `json:"header,omitempty"`
	HTTPAcceptGzip                bool     `json:"http-accept-gzip,omitempty,string"`
	HTTPAuthChallenge             bool     `json:"http-auth-challenge,omitempty,string"`
	HTTPNoCache                   bool     `json:"http-no-cache,omitempty,string"`
	HTTPPasswd                    string   `json:"http-passwd,omitempty"`
	HTTPProxy                     string   `json:"http-proxy,omitempty"`
	HTTPProxyPasswd               string   `json:"http-proxy-passwd,omitempty"`
	HTTPProxyUser                 string   `json:"http-proxy-user,omitempty"`
	HTTPUser                      string   `json:"http-user,omitempty"`
	HTTPSProxy                    string   `json:"https-proxy,omitempty"`
	HTTPSProxyPasswd              string   `json:"https-proxy-passwd,omitempty"`
	HTTPSProxyUser                string   `json:"https-proxy-user,omitempty"`
	IndexOut                      uint     `json:"index-out,omitempty,string"`
	LowestSpeedLimit              uint     `json:"lowest-speed-limit,omitempty,string"`
	MaxConnectionPerServer        uint     `json:"max-connection-per-server,omitempty,string"`
	MaxDownloadLimit              uint     `json:"max-download-limit,omitempty,string"`
	MaxFileNotFound               uint     `json:"max-file-not-found,omitempty,string"`
	MaxMMapLimit                  uint     `json:"max-mmap-limit,omitempty,string"`
	MaxResumeFailureTries         uint     `json:"max-resume-failure-tries,omitempty,string"`
	MaxTries                      uint     `json:"max-tries,omitempty,string"`
	MaxUploadLimit                uint     `json:"max-upload-limit,omitempty,string"`
	MetalinkBaseURI               string   `json:"metalink-base-uri,omitempty"`
	MetalinkEnableUniqueProtocol  bool     `json:"metalink-enable-unique-protocol,omitempty,string"`
	MetalinkLanguage              string   `json:"metalink-language,omitempty"`
	MetalinkLocation              string   `json:"metalink-location,omitempty"`
	MetalinkOS                    string   `json:"metalink-os,omitempty"`
	MetalinkPreferredProtocol     string   `json:"metalink-preferred-protocol,omitempty"`
	MetalinkVersion               string   `json:"metalink-version,omitempty"`
	MinSplitSize                  uint     `json:"min-split-size,omitempty,string"`
	NoFileAllocationLimit         bool     `json:"no-file-allocation-limit,omitempty,string"`
	NoNetrc                       bool     `json:"no-netrc,omitempty,string"`
	NoProxy                       bool     `json:"no-proxy,omitempty,string"`
	Out                           string   `json:"out,omitempty"`
	ParameterizedURI              string   `json:"parameterized-uri,omitempty"`
	Pause                         bool     `json:"pause,omitempty,string"`
	PauseMetadata                 bool     `json:"pause-metadata,omitempty,string"`
	PieceLength                   string   `json:"piece-length,omitempty"`
	ProxyMethod                   string   `json:"proxy-method,omitempty"`
	RealtimeChunkChecksum         string   `json:"realtime-chunk-checksum,omitempty"`
	Referer                       string   `json:"referer,omitempty"`
	RemoteTime                    bool     `json:"remote-time,omitempty,string"`
	RemoveControlFile             string   `json:"remove-control-file,omitempty"`
	RetryWait                     uint     `json:"retry-wait,omitempty,string"`
	ReuseURI                      bool     `json:"reuse-uri,omitempty,string"`
	RPCSaveUploadMetadata         string   `json:"rpc-save-upload-metadata,omitempty"`
	SeedRatio                     float32  `json:"seed-ratio,omitempty,string"`
	SeedTime                      uint     `json:"seed-time,omitempty,string"`
	SelectFile                    bool     `json:"select-file,omitempty,string"`
	Split                         uint     `json:"split,omitempty,string"`
	SSHHostKeyMD                  string   `json:"ssh-host-key-md,omitempty"`
	StreamPieceSelector           string   `json:"stream-piece-selector,omitempty"`
	Timeout                       uint     `json:"timeout,omitempty,string"`
	URISelector                   string   `json:"uri-selector,omitempty"`
	UseHead                       bool     `json:"use-head,omitempty,string"`
	UserAgent                     string   `json:"user-agent,omitempty"`
}

Options represents the aria2 input file options

type Peer

type Peer struct {
	ID   string `json:"peerId"`      // Percent-encoded peer ID.
	IP   string `json:"ip"`          // IP address of the peer.
	Port uint16 `json:"port,string"` // Port number of the peer

	// 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.
	BitField      string `json:"bitfield"`
	AmChoking     bool   `json:"amChoking,string"`     // true if aria2 is choking the peer. Otherwise false.
	PeerChoking   bool   `json:"peerChoking,string"`   // true if the peer is choking aria2. Otherwise false.
	DownloadSpeed uint   `json:"downloadSpeed,string"` // Download speed (byte/sec) that this client obtains from the peer
	UploadSpeed   uint   `json:"uploadSpeed,string"`   // Upload speed (byte/sec) that this client uploads to the peer
	Seeder        bool   `json:"seeder,string"`        // true if this peer is a seeder. Otherwise false
}

Peer represents a torrent peer

type PositionSetBehaviour

type PositionSetBehaviour string

PositionSetBehaviour determines how a position is to be interpreted

const (
	// SetPositionStart sets the position relative to the start
	SetPositionStart PositionSetBehaviour = "POS_SET"

	// SetPositionEnd sets the position relative to the end
	SetPositionEnd PositionSetBehaviour = "POS_END"

	// SetPositionRelative sets the position relative to the current position
	SetPositionRelative PositionSetBehaviour = "POS_CUR"
)

type Server

type Server struct {
	URI string `json:"uri"` // Original URI.

	// This is the URI currently used for downloading.
	// If redirection is involved, currentUri and uri may differ.
	CurrentURI    string `json:"currentUri"`
	DownloadSpeed uint   `json:"downloadSpeed,string"` // Download speed (byte/sec)
}

Server represents an endpoint which data is being downloaded from

type SessionInfo

type SessionInfo struct {
	// Session ID, which is generated each time when aria2 is invoked
	ID string `json:"sessionId"`
}

SessionInfo holds the session information of aria2

type Stats

type Stats struct {
	DownloadSpeed uint `json:"downloadSpeed,string"` // Overall download speed (byte/sec).
	UploadSpeed   uint `json:"uploadSpeed,string"`   // Overall upload speed(byte/sec).
	NumActive     uint `json:"numActive,string"`     // The number of active downloads.
	NumWaiting    uint `json:"numWaiting,string"`    // The number of waiting downloads.

	// The number of stopped downloads in the current session.
	// This value is capped by the MaxDownloadResult option.
	NumStopped uint `json:"numStopped,string"`

	// The number of stopped downloads in the current session and not capped by the MaxDownloadResult option.
	NumStoppedTotal uint `json:"numStoppedTotal,string"`
}

Stats holds aria2 statistics

type Status

type Status struct {
	GID             string         `json:"gid"`                    // gid of the download
	Status          DownloadStatus `json:"status"`                 // Download status
	TotalLength     uint           `json:"totalLength,string"`     // Total length of the download in bytes
	CompletedLength uint           `json:"completedLength,string"` // Completed length of the download in bytes
	UploadLength    uint           `json:"uploadLength,string"`    // Uploaded length of the download in bytes

	// 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 will be an empty string.
	BitField      string `json:"bitfield"`
	DownloadSpeed uint   `json:"downloadSpeed,string"` // Download speed of this download measured in bytes/sec
	UploadSpeed   uint   `json:"uploadSpeed,string"`   // Upload speed of this download measured in bytes/sec
	InfoHash      string `json:"infoHash"`             // InfoHash. BitTorrent only

	// The number of seeders aria2 has connected to. BitTorrent only
	NumSeeders uint `json:"numSeeders,string"`

	// true if the local endpoint is a seeder. Otherwise false. BitTorrent only
	Seeder       bool       `json:"seeder,string"`
	PieceLength  uint       `json:"pieceLength,string"` // Piece length in bytes
	NumPieces    uint       `json:"numPieces,string"`   // The number of pieces
	Connections  uint       `json:"connections,string"` // The number of peers/servers aria2 has connected to
	ErrorCode    ExitStatus `json:"errorCode,string"`   // The code of the last error for this item, if any.
	ErrorMessage string     `json:"errorMessage"`       // The human readable error message associated to ErrorCode

	// 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 will be an empty slice
	FollowedBy []string `json:"followedBy"`

	// The reverse link for followedBy.
	// A download included in followedBy has this object’s GID in its following
	// value.
	Following string `json:"following"`

	// 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 will be an empty string
	BelongsTo  string           `json:"belongsTo"`
	Dir        string           `json:"dir"`        // Directory to save files
	Files      []File           `json:"files"`      // Slice of files.
	BitTorrent BitTorrentStatus `json:"bittorrent"` // Information retrieved from the .torrent (file). BitTorrent only

	// The number of verified number of bytes while the files are being has
	// checked.
	// This key exists only when this download is being hash checked
	VerifiedLength uint `json:"verifiedLength,string"`

	// true if this download is waiting for the hash check in a queue.
	VerifyIntegrityPending bool `json:"verifyIntegrityPending,string"`
}

Status holds information for a download.

type TorrentMode

type TorrentMode string

TorrentMode represents the file mode of the torrent

const (
	// TorrentModeSingle represents the file mode single
	TorrentModeSingle TorrentMode = "single"
	// TorrentModeMulti represents the file mode multi
	TorrentModeMulti TorrentMode = "multi"
)

type UNIXTime

type UNIXTime struct {
	time.Time
}

UNIXTime is a wrapper around time.Time that marshals to a unix timestamp.

func (UNIXTime) MarshalJSON

func (t UNIXTime) MarshalJSON() ([]byte, error)

MarshalJSON converts the time to a unix timestamp

func (*UNIXTime) UnmarshalJSON

func (t *UNIXTime) UnmarshalJSON(data []byte) error

UnmarshalJSON loads a unix timestamp

type URI

type URI struct {
	URI    string    `json:"uri"`
	Status URIStatus `json:"status"` // Status of the uri
}

URI represents a uri used in a download

type URIStatus

type URIStatus string

URIStatus represents the status of an uri.

const (
	// URIUsed represents the state of the uri being used
	URIUsed URIStatus = "used"
	// URIWaiting represents the state of the uri waiting in the queue
	URIWaiting URIStatus = "waiting"
)

type UnsubscribeFunc

type UnsubscribeFunc func() bool

UnsubscribeFunc is a function which when called, unsubscribes from an event.

type VersionInfo

type VersionInfo struct {
	Version         string   `json:"version"`         // Version number of aria2 as a string.
	EnabledFeatures []string `json:"enabledFeatures"` // Slice of enabled features. Each feature is given as a string.
}

VersionInfo represents the version information sent by aria2

Directories

Path Synopsis
internal
pkg/wsrpc
Package wsrpc provides a ReadWriteCloser which operates on a WebSocket connection.
Package wsrpc provides a ReadWriteCloser which operates on a WebSocket connection.
pkg
aria2proto
Package aria2proto provides the aria2 rpc protocol commands and events.
Package aria2proto provides the aria2 rpc protocol commands and events.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL