delugeclient

package module
v0.0.0-...-4eeeac7 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2022 License: GPL-2.0 Imports: 13 Imported by: 1

README

go-libdeluge

Go library for native RPC connection to a Deluge daemon; it uses go-rencode for the RPC protocol serialization/deserialization.

Release blog post.

License

GNU GPL version 2

How to build

This project uses Go modules. You can build it with make:

make

How to use

The library by itself is a Go package and needs to be embedded in an UI or CLI application.

	// you can use NewV1 to create a client for Deluge v1.3
	deluge := delugeclient.NewV2(delugeclient.Settings{
		Hostname:              "localhost",
		Port:                  58846,
		Login:                 "localclient",
		Password:              "*************",
	})

	// perform connection to Deluge server
	err := deluge.Connect()

	// ... use the client methods

To debug the library you may want to set DebugServerResponses to true.

Example CLI application

An example CLI application is available through:

go get github.com/gdm85/go-libdeluge/delugecli

Example usage:

DELUGE_PASSWORD="mypassword" bin/delugecli -add magnet:?xt=urn:btih:C1939CA413B9AFCC34EA0CF3C128574E93FF6CB0&tr=http%3A%2F%2Ftorrent.ubuntu.com%3A6969%2Fannounce

This will start downloading the latest Ubuntu 14.04 LTS server ISO. Multiple magnet URIs are supported as command-line arguments; run bin/delugecli alone to see all available options and their description.

Supported deluge versions

Both deluge v2.0+ and v1.3+ are supported with the two different constructors NewV2 and NewV1.

RPC API supported methods

  • daemon.login
  • daemon.info
  • daemon.authorized_call
  • daemon.get_method_list
  • daemon.get_version
  • daemon.shutdown
  • core.add_torrent_file
  • core.add_torrent_file_async
  • core.add_torrent_files
  • core.add_torrent_magnet
  • core.add_torrent_url
  • core.connect_peer
  • core.create_account
  • core.create_torrent
  • core.disable_plugin
  • core.enable_plugin
  • core.force_reannounce
  • core.force_recheck
  • core.get_auth_levels_mappings
  • core.get_available_plugins
  • core.get_completion_paths
  • core.get_config
  • core.get_config_value
  • core.get_config_values
  • core.get_enabled_plugins
  • core.get_external_ip
  • core.get_filter_tree
  • core.get_free_space
  • core.get_known_accounts
  • core.get_libtorrent_version
  • core.get_listen_port
  • core.get_path_size
  • core.get_proxy
  • core.get_session_state
  • core.get_session_status
  • core.get_torrent_status
  • core.get_torrents_status
  • core.glob
  • core.is_session_paused
  • core.move_storage
  • core.pause_session
  • core.pause_torrent
  • core.pause_torrents
  • core.prefetch_magnet_metadata
  • core.queue_bottom
  • core.queue_down
  • core.queue_top
  • core.queue_up
  • core.remove_account
  • core.remove_torrent
  • core.remove_torrents
  • core.rename_files
  • core.rename_folder
  • core.rescan_plugins
  • core.resume_session
  • core.resume_torrent
  • core.resume_torrents
  • core.set_config
  • core.set_torrent_options
  • core.set_torrent_trackers
  • core.test_listen_port
  • core.update_account
  • core.upload_plugin

Plugins

Plugins can be used by calling the relative method and checking if the result is not nil, example:

	p, err := deluge.LabelPlugin()
	if err != nil {
		panic(err)
	}
	if p == nil {
		println("Label plugin not available")
		return
	}

	// call plugin methods
	labelsByTorrent, err := p.GetTorrentsLabels(delugeclient.StateUnspecified, nil)

Label

RPC API supported methods
  • label.add
  • label.get_config
  • label.get_labels
  • label.get_options
  • label.remove
  • label.set_config
  • label.set_options
  • label.set_torrent

Documentation

Overview

Package delugeclient allows calling native RPC methods on a remote deluge server.

Index

Constants

View Source
const (
	// DefaultReadWriteTimeout is the default timeout for I/O operations with the Deluge server.
	DefaultReadWriteTimeout = time.Second * 30
)
View Source
const Deluge2ProtocolVersion = 1

Deluge2ProtocolVersion is the protocol version used with Deluge v2+

Variables

View Source
var (
	// ErrAlreadyClosed is returned when connection is already closed.
	ErrAlreadyClosed = errors.New("connection is already closed")
	// ErrInvalidDictionaryResponse is returned when the expected dictionary as list is not received.
	ErrInvalidDictionaryResponse = errors.New("expected dictionary as list response")
	// ErrInvalidReturnValue is returned when the returned value received from server is invalid.
	ErrInvalidReturnValue = errors.New("invalid return value")
)

Functions

This section is empty.

Types

type Account

type Account struct {
	Username  string
	Password  string
	AuthLevel AuthLevel
}

Account is a user account inside the auth file.

type AuthLevel

type AuthLevel string

AuthLevel is an Auth Level string understood by Deluge

const (
	AuthLevelNone     AuthLevel = "NONE"
	AuthLevelReadonly AuthLevel = "READONLY"
	AuthLevelNormal   AuthLevel = "NORMAL"
	AuthLevelAdmin    AuthLevel = "ADMIN"
	AuthLevelDefault  AuthLevel = AuthLevelNormal
)

The auth level names, as defined in https://github.com/deluge-torrent/deluge/blob/deluge-2.0.3/deluge/core/authmanager.py#L33-L37

type Client

type Client struct {
	DebugServerResponses []*bytes.Buffer
	// contains filtered or unexported fields
}

Client is a Deluge RPC client.

func NewV1

func NewV1(s Settings) *Client

NewV1 returns a Deluge client for v1.3 servers.

func (*Client) AddTorrentFile

func (c *Client) AddTorrentFile(fileName, fileContentBase64 string, options *Options) (string, error)

AddTorrentFile adds a torrent via a base64 encoded file and returns the torrent hash.

func (*Client) AddTorrentMagnet

func (c *Client) AddTorrentMagnet(magnetURI string, options *Options) (string, error)

AddTorrentMagnet adds a torrent via magnet URI and returns the torrent hash.

func (*Client) AddTorrentURL

func (c *Client) AddTorrentURL(url string, options *Options) (string, error)

AddTorrentURL adds a torrent via a URL and returns the torrent hash.

func (*Client) Close

func (c *Client) Close() error

Close closes the connection of a Deluge client.

func (*Client) Connect

func (c *Client) Connect() error

Connect performs connection to a Deluge daemon and logs in.

func (*Client) DaemonLogin

func (c *Client) DaemonLogin() error

DaemonLogin performs login to the Deluge daemon.

func (*Client) DaemonVersion

func (c *Client) DaemonVersion() (string, error)

DaemonVersion returns the running daemon version.

func (*Client) DisablePlugin

func (c *Client) DisablePlugin(name string) error

DisablePlugin disables the plugin with the given name.

func (*Client) EnablePlugin

func (c *Client) EnablePlugin(name string) error

EnablePlugin enables the plugin with the given name.

func (*Client) ForceReannounce

func (c *Client) ForceReannounce(ids []string) error

ForceReannounce will reannounce torrent status to associated tracker(s).

func (*Client) GetAvailablePlugins

func (c *Client) GetAvailablePlugins() ([]string, error)

GetAvailablePlugins returns a list of available plugins.

func (*Client) GetEnabledPlugins

func (c *Client) GetEnabledPlugins() ([]string, error)

GetEnabledPlugins returns a list of enabled plugins.

func (*Client) GetFreeSpace

func (c *Client) GetFreeSpace(path string) (int64, error)

GetFreeSpace returns the available free space; path is optional.

func (*Client) GetLibtorrentVersion

func (c *Client) GetLibtorrentVersion() (string, error)

GetLibtorrentVersion returns the libtorrent version.

func (*Client) GetListenPort

func (c *Client) GetListenPort() (uint16, error)

GetListenPort returns the listen port of the deluge daemon.

func (*Client) GetSessionStatus

func (c *Client) GetSessionStatus() (*SessionStatus, error)

GetSessionStatus retrieves session status and statistics.

func (*Client) LabelPlugin

func (c *Client) LabelPlugin() (*LabelPlugin, error)

LabelPlugin returns the label plugin if enabled or nil. An error is returned if enabled plugins could not be retrieved.

func (*Client) MethodsList

func (c *Client) MethodsList() ([]string, error)

MethodsList returns a list of available methods on server.

func (*Client) MoveStorage

func (c *Client) MoveStorage(torrentIDs []string, dest string) error

MoveStorage will move the storage location of the group of torrents with the given IDs.

func (*Client) PauseTorrents

func (c *Client) PauseTorrents(ids ...string) error

PauseTorrents pauses a group of torrents with the given IDs.

func (*Client) RemoveTorrent

func (c *Client) RemoveTorrent(id string, rmFiles bool) (bool, error)

RemoveTorrent removes a single torrent, returning true if successful. If `rmFiles` is set it also tries to delete all downloaded data for the specified torrent.

func (*Client) RemoveTorrents

func (c *Client) RemoveTorrents(ids []string, rmFiles bool) ([]TorrentError, error)

RemoveTorrents tries to remove multiple torrents at once. If `rmFiles` is set it also tries to delete all downloaded data for the specified torrents. If errors were encountered the returned list will be a list of TorrentErrors. On success an empty list of errors is returned.

The user should not rely on files being removed or torrents being removed from the session, just because no errors have been returned, as returned errors will primarily indicate that some of the supplied torrent hashes were invalid.

func (*Client) ResumeTorrents

func (c *Client) ResumeTorrents(ids ...string) error

ResumeTorrents resumes a group of torrents with the given IDs.

func (*Client) SessionState

func (c *Client) SessionState() ([]string, error)

SessionState returns the current session state.

func (*Client) SetTorrentOptions

func (c *Client) SetTorrentOptions(id string, options *Options) error

SetTorrentOptions updates options for the torrent with the given hash.

func (*Client) SetTorrentTracker

func (c *Client) SetTorrentTracker(id, trackerURL string) error

SetTorrentTracker sets the primary tracker for the torrent with the given hash to be `trackerURL`.

func (*Client) TestListenPort

func (c *Client) TestListenPort() (bool, error)

TestListenPort checks if the active port is open.

func (*Client) TorrentStatus

func (c *Client) TorrentStatus(hash string) (*TorrentStatus, error)

TorrentStatus returns the status of the torrent with specified hash.

func (*Client) TorrentsStatus

func (c *Client) TorrentsStatus(state TorrentState, hashes []string) (map[string]*TorrentStatus, error)

TorrentsStatus returns the status of torrents matching the specified state and list of hashes. Both state and list of hashes are optional.

type ClientV2

type ClientV2 struct {
	Client
}

func NewV2

func NewV2(s Settings) *ClientV2

NewV2 returns a Deluge client for v1.3 servers.

func (*ClientV2) CreateAccount

func (c *ClientV2) CreateAccount(account Account) (bool, error)

CreateAccount creates a new Deluge user with the supplied username, password and permission level. The authenticated user must have an authLevel of ADMIN to succeed.

func (*ClientV2) KnownAccounts

func (c *ClientV2) KnownAccounts() ([]Account, error)

KnownAccounts returns all known accounts, including password and permission levels.

func (*ClientV2) RemoveAccount

func (c *ClientV2) RemoveAccount(username string) (bool, error)

RemoveAccount will delete an existing username. The authenticated user must have an authLevel of ADMIN to succeed.

func (*ClientV2) UpdateAccount

func (c *ClientV2) UpdateAccount(account Account) (bool, error)

UpdateAccount sets a new password and permission level for a account. The authenticated user must have an authLevel of ADMIN to succeed.

type DelugeClient

type DelugeClient interface {
	Connect() error
	Close() error

	DaemonLogin() error
	MethodsList() ([]string, error)
	DaemonVersion() (string, error)
	GetFreeSpace(string) (int64, error)
	GetLibtorrentVersion() (string, error)
	AddTorrentMagnet(magnetURI string, options *Options) (string, error)
	AddTorrentURL(url string, options *Options) (string, error)
	AddTorrentFile(fileName, fileContentBase64 string, options *Options) (string, error)
	RemoveTorrents(ids []string, rmFiles bool) ([]TorrentError, error)
	RemoveTorrent(id string, rmFiles bool) (bool, error)
	PauseTorrents(ids ...string) error
	ResumeTorrents(ids ...string) error
	TorrentsStatus(state TorrentState, ids []string) (map[string]*TorrentStatus, error)
	TorrentStatus(id string) (*TorrentStatus, error)
	MoveStorage(torrentIDs []string, dest string) error
	SetTorrentTracker(id, tracker string) error
	SetTorrentOptions(id string, options *Options) error
	SessionState() ([]string, error)
	ForceReannounce(ids []string) error
	GetAvailablePlugins() ([]string, error)
	GetEnabledPlugins() ([]string, error)
	EnablePlugin(name string) error
	DisablePlugin(name string) error
	TestListenPort() (bool, error)
	GetListenPort() (uint16, error)
	GetSessionStatus() (*SessionStatus, error)
}

DelugeClient is an interface for v1.3 and v2 Deluge servers.

type DelugeResponse

type DelugeResponse struct {

	// only in rpcError
	RPCError
	// contains filtered or unexported fields
}

DelugeResponse is a response returned from a completed RPC call.

func (*DelugeResponse) IsError

func (dr *DelugeResponse) IsError() bool

IsError returns true when the response is an error.

func (*DelugeResponse) String

func (dr *DelugeResponse) String() string

type File

type File struct {
	Index  int64
	Size   int64
	Offset int64
	Path   string
}

File is a Deluge torrent file.

type LabelPlugin

type LabelPlugin struct {
	*Client
}

LabelPlugin exposes label plugin methods.

func (LabelPlugin) AddLabel

func (p LabelPlugin) AddLabel(label string) error

AddLabel adds a new label definition.

func (LabelPlugin) GetLabels

func (p LabelPlugin) GetLabels() ([]string, error)

GetLabels returns a list of the available labels that can be assigned to torrents.

func (LabelPlugin) GetTorrentLabel

func (p LabelPlugin) GetTorrentLabel(hash string) (string, error)

GetTorrentLabel returns the label of the specified torrent.

func (LabelPlugin) GetTorrentsLabels

func (p LabelPlugin) GetTorrentsLabels(state TorrentState, ids []string) (map[string]string, error)

GetTorrentsLabels filters torrents by state and/or IDs and returns their label.

func (LabelPlugin) RemoveLabel

func (p LabelPlugin) RemoveLabel(label string) error

RemoveLabel removes a label definition.

func (LabelPlugin) SetTorrentLabel

func (p LabelPlugin) SetTorrentLabel(hash, label string) error

SetTorrentLabel adds or replaces the label for the specified torrent.

type Options

type Options struct {
	MaxConnections            *int
	MaxUploadSlots            *int
	MaxUploadSpeed            *int
	MaxDownloadSpeed          *int
	PrioritizeFirstLastPieces *bool
	PreAllocateStorage        *bool // compact_allocation for v1
	DownloadLocation          *string
	AutoManaged               *bool
	StopAtRatio               *bool
	StopRatio                 *float32
	RemoveAtRatio             *float32
	MoveCompleted             *bool
	MoveCompletedPath         *string
	AddPaused                 *bool

	// V2 defines v2-only options
	V2 V2Options
}

Options used when adding a torrent magnet/URL. Valid options for v2: https://github.com/deluge-torrent/deluge/blob/deluge-2.0.3/deluge/core/torrent.py#L167-L183 Valid options for v1: https://github.com/deluge-torrent/deluge/blob/1.3-stable/deluge/core/torrent.py#L83-L96

type Peer

type Peer struct {
	Client    string
	IP        string
	Progress  float32
	Seed      int64
	DownSpeed int64
	UpSpeed   int64
	Country   string
}

Peer is a Deluge torrent peer.

type RPCError

type RPCError struct {
	ExceptionType    string
	ExceptionMessage string
	TraceBack        string
}

RPCError is an error returned by RPC calls.

func (RPCError) Error

func (e RPCError) Error() string

type SerialMismatchError

type SerialMismatchError struct {
	ExpectedID int64
	ReceivedID int64
}

SerialMismatchError is the error returned when server replied with an out-of-order response.

func (SerialMismatchError) Error

func (e SerialMismatchError) Error() string

type SessionStatus

type SessionStatus struct {
	HasIncomingConnections bool
	UploadRate             float32
	DownloadRate           float32
	PayloadUploadRate      float32
	PayloadDownloadRate    float32
	TotalDownload          int32
	TotalUpload            int32
	NumPeers               int16
	DhtNodes               int16
}

SessionStatus contains basic session status and statistics.

type Settings

type Settings struct {
	Hostname string
	Port     uint
	Login    string
	Password string
	Logger   *log.Logger
	// ReadWriteTimeout is the timeout for read/write operations on the TCP stream.
	ReadWriteTimeout time.Duration
	// DebugServerResponses is used populate the DebugServerResponses slice on the client with
	// byte buffers containing the raw bytes as received from the Deluge server.
	DebugServerResponses bool
}

Settings defines all settings for a Deluge client connection.

type TorrentError

type TorrentError struct {
	// ID is the hash of the torrent that experienced an error
	ID      string
	Message string
}

TorrentError is a tuple of a torrent id and an error message, returned by methods that manipulate many torrents at once.

func (TorrentError) Error

func (t TorrentError) Error() string

type TorrentState

type TorrentState string
const (
	StateUnspecified TorrentState = ""
	StateActive      TorrentState = "Active"
	StateAllocating  TorrentState = "Allocating"
	StateChecking    TorrentState = "Checking"
	StateDownloading TorrentState = "Downloading"
	StateSeeding     TorrentState = "Seeding"
	StatePaused      TorrentState = "Paused"
	StateError       TorrentState = "Error"
	StateQueued      TorrentState = "Queued"
	StateMoving      TorrentState = "Moving"
)

See all defined torrent states here: https://github.com/deluge-torrent/deluge/blob/deluge-2.0.3/deluge/common.py#L70-L78 Plus the special 'Active' state.

type TorrentStatus

type TorrentStatus struct {
	ActiveTime           int64
	CompletedTime        int64   `rencode:"v2only"`
	TimeAdded            float32 // most times an integer
	DistributedCopies    float32
	ETA                  float32 // most times an integer
	Progress             float32 // max is 100
	Ratio                float32
	IsFinished           bool
	IsSeed               bool
	Private              bool
	DownloadLocation     string `rencode:"v2only"`
	DownloadPayloadRate  int64
	Name                 string
	NextAnnounce         int64
	NumPeers             int64
	NumPieces            int64
	NumSeeds             int64
	PieceLength          int64
	SeedingTime          int64
	State                string
	TotalDone            int64
	TotalPeers           int64
	TotalSeeds           int64
	TotalSize            int64
	TotalUploaded        int64
	TotalPayloadDownload int64
	TotalPayloadUpload   int64
	TrackerHost          string
	TrackerStatus        string
	UploadPayloadRate    int64

	Files          []File
	Peers          []Peer
	FilePriorities []int64
	FileProgress   []float32
}

TorrentStatus contains commonly used torrent attributes, as reported by the deluge server. The full list of potentially available attributes can be found here: https://github.com/deluge-torrent/deluge/blob/deluge-2.0.3/deluge/core/torrent.py#L1033-L1143 If a new field is added to this struct it should also be added to the statusKeys map.

type V2

type V2 interface {
	DelugeClient

	KnownAccounts() ([]Account, error)
	CreateAccount(account Account) (bool, error)
	RemoveAccount(username string) (bool, error)
	UpdateAccount(account Account) (bool, error)
}

V2 is an interface for v2 Deluge clients.

type V2Options

type V2Options struct {
	SequentialDownload *bool
	Shared             *bool
	SuperSeeding       *bool
}

Directories

Path Synopsis
Command line util to issue requests against a headless deluge server.
Command line util to issue requests against a headless deluge server.

Jump to

Keyboard shortcuts

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