transmissionrpc

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: May 4, 2021 License: MIT Imports: 16 Imported by: 1

README

TransmissionRPC

go.dev reference Go report card

Golang bindings to Transmission (bittorrent) RPC interface.

Even if there is some high level wrappers/helpers, the goal of this lib is to stay close to the original API in terms of methods and payloads while enhancing certain types to be more "golangish": timestamps are converted from/to time.Time, numeric durations in time.Duration, booleans in numeric form are converted to real bool, etc...

Also payload generation aims to be precise: when several values can be added to a payload, only instanciated values will be forwarded (and kept !) to the final payload. This means that the default JSON marshalling (with omitempty) can't always be used and therefor a manual, reflect based, approach is used to build the final payload and accurately send what the user have instanciated, even if a value is at its default type value.

This lib follows the transmission v15 RPC specification.

Getting started

First the main client object must be instantiated with New(). In its basic form only host/ip, username and password must be provided. Default will apply for port (9091) rpc URI (/transmission/rpc) and others values.

transmissionbt := transmissionrpc.New("127.0.0.1", "rpcuser", "rpcpass", nil)

But advanced values can also be configured to your liking using AdvancedConfig. Each value of AdvancedConfig with a type default value will be replaced by the lib default value, so you can set only the ones you want:

transmissionbt := transmissionrpc.New("bt.mydomain.net", "rpcuser", "rpcpass",
    &transmissionrpc.AdvancedConfig{
        HTTPS: true,
        Port:  443,
    })

The remote RPC version can be checked against this library before starting to operate:

ok, serverVersion, serverMinimumVersion, err := transmission.RPCVersion()
if err != nil {
    panic(err)
}
if !ok {
    panic(fmt.Sprintf("Remote transmission RPC version (v%d) is incompatible with the transmission library (v%d): remote needs at least v%d",
        serverVersion, transmissionrpc.RPCVersion, serverMinimumVersion))
}
fmt.Printf("Remote transmission RPC version (v%d) is compatible with our transmissionrpc library (v%d)\n",
    serverVersion, transmissionrpc.RPCVersion)

Features

Torrent Requests
Torrent Action Requests

Each rpc methods here can work with ID list, hash list or recently-active magic word. Therefor, there is 3 golang method variants for each of them.

transmissionbt.TorrentXXXXIDs(...)
transmissionbt.TorrentXXXXHashes(...)
transmissionbt.TorrentXXXXRecentlyActive()
  • torrent-start

Check TorrentStartIDs(), TorrentStartHashes() and TorrentStartRecentlyActive().

Ex:

err := transmissionbt.TorrentStartIDs([]int64{55})
if err != nil {
    fmt.Fprintln(os.Stderr, err)
} else {
    fmt.Println("yay")
}
  • torrent-start-now

Check TorrentStartNowIDs(), TorrentStartNowHashes() and TorrentStartNowRecentlyActive().

Ex:

err := transmissionbt.TorrentStartNowHashes([]string{"f07e0b0584745b7bcb35e98097488d34e68623d0"})
if err != nil {
    fmt.Fprintln(os.Stderr, err)
} else {
    fmt.Println("yay")
}
  • torrent-stop

Check TorrentStopIDs(), TorrentStopHashes() and TorrentStopRecentlyActive().

Ex:

err := transmissionbt.TorrentStopIDs([]int64{55})
if err != nil {
    fmt.Fprintln(os.Stderr, err)
} else {
    fmt.Println("yay")
}
  • torrent-verify

Check TorrentVerifyIDs(), TorrentVerifyHashes() and TorrentVerifyRecentlyActive().

Ex:

err := transmissionbt.TorrentVerifyHashes([]string{"f07e0b0584745b7bcb35e98097488d34e68623d0"})
if err != nil {
    fmt.Fprintln(os.Stderr, err)
} else {
    fmt.Println("yay")
}
  • torrent-reannounce

Check TorrentReannounceIDs(), TorrentReannounceHashes() and TorrentReannounceRecentlyActive().

Ex:

err := transmissionbt.TorrentReannounceRecentlyActive()
if err != nil {
    fmt.Fprintln(os.Stderr, err)
} else {
    fmt.Println("yay")
}
Torrent Mutators
  • torrent-set

Mapped as TorrentSet().

Ex: apply a 1 MB/s limit to a torrent.

uploadLimited := true
uploadLimitKBps := int64(1000)
err := transmissionbt.TorrentSet(&transmissionrpc.TorrentSetPayload{
    IDs:           []int64{55},
    UploadLimited: &uploadLimited,
    UploadLimit:   &uploadLimitKBps,
})
if err != nil {
    fmt.Fprintln(os.Stderr, err)
} else {
    fmt.Println("yay")
}

There is a lot more mutators available.

Torrent Accessors
  • torrent-get

All fields for all torrents with TorrentGetAll():

torrents, err := transmissionbt.TorrentGetAll()
if err != nil {
    fmt.Fprintln(os.Stderr, err)
} else {
    fmt.Println(torrents) // meh it's full of pointers
}

All fields for a restricted list of ids with TorrentGetAllFor():

torrents, err := transmissionbt.TorrentGetAllFor([]int64{31})
if err != nil {
    fmt.Fprintln(os.Stderr, err)
} else {
    fmt.Println(torrents) // meh it's still full of pointers
}

Some fields for some torrents with the low level accessor TorrentGet():

torrents, err := transmissionbt.TorrentGet([]string{"status"}, []int64{54, 55})
if err != nil {
    fmt.Fprintln(os.Stderr, err)
} else {
    for _, torrent := range torrents {
        fmt.Println(torrent.Status) // the only instanciated field, as requested
    }
}

Some fields for all torrents, still with the low level accessor TorrentGet():

torrents, err := transmissionbt.TorrentGet([]string{"id", "name", "hashString"}, nil)
if err != nil {
    fmt.Fprintln(os.Stderr, err)
} else {
    for _, torrent := range torrents {
        fmt.Println(torrent.ID)
        fmt.Println(torrent.Name)
        fmt.Println(torrent.HashString)
    }
}

Valid fields name can be found as JSON tag on the Torrent struct.

Adding a Torrent
  • torrent-add

Adding a torrent from a file (using TorrentAddFile wrapper):

filepath := "/home/hekmon/Downloads/ubuntu-17.10.1-desktop-amd64.iso.torrent"
torrent, err := transmissionbt.TorrentAddFile(filepath)
if err != nil {
    fmt.Fprintln(os.Stderr, err)
} else {
    // Only 3 fields will be returned/set in the Torrent struct
    fmt.Println(*torrent.ID)
    fmt.Println(*torrent.Name)
    fmt.Println(*torrent.HashString)
}

Adding a torrent from a file (using TorrentAddFileDownloadDir wrapper) to a specified DownloadDir (this allows for separation of downloads to target folders):

filepath := "/home/hekmon/Downloads/ubuntu-17.10.1-desktop-amd64.iso.torrent"
torrent, err := transmissionbt.TorrentAddFileDownloadDir(filepath, "/path/to/other/download/dir")
if err != nil {
    fmt.Fprintln(os.Stderr, err)
} else {
    // Only 3 fields will be returned/set in the Torrent struct
    fmt.Println(*torrent.ID)
    fmt.Println(*torrent.Name)
    fmt.Println(*torrent.HashString)
}

Adding a torrent from an URL (ex: a magnet) with the real TorrentAdd method:

magnet := "magnet:?xt=urn:btih:f07e0b0584745b7bcb35e98097488d34e68623d0&dn=ubuntu-17.10.1-desktop-amd64.iso&tr=http%3A%2F%2Ftorrent.ubuntu.com%3A6969%2Fannounce&tr=http%3A%2F%2Fipv6.torrent.ubuntu.com%3A6969%2Fannounce"
torrent, err := btserv.TorrentAdd(&transmissionrpc.TorrentAddPayload{
    Filename: &magnet,
})
if err != nil {
    fmt.Fprintln(os.Stderr, err)
} else {
    // Only 3 fields will be returned/set in the Torrent struct
    fmt.Println(*torrent.ID)
    fmt.Println(*torrent.Name)
    fmt.Println(*torrent.HashString)
}

Which would output:

55
ubuntu-17.10.1-desktop-amd64.iso
f07e0b0584745b7bcb35e98097488d34e68623d0

Adding a torrent from a file, starting it paused:

filepath := "/home/hekmon/Downloads/ubuntu-17.10.1-desktop-amd64.iso.torrent"
b64, err := transmissionrpc.File2Base64(filepath)
if err != nil {
	fmt.Fprintf(os.Stderr, "can't encode '%s' content as base64: %v", filepath, err)
} else {
	// Prepare and send payload
	paused := true
	torrent, err := transmissionbt.TorrentAdd(&transmissionrpc.TorrentAddPayload{MetaInfo: &b64, Paused: &paused})
}
Removing a Torrent
  • torrent-remove

Mapped as TorrentRemove().

Moving a Torrent
  • torrent-set-location

Mapped as TorrentSetLocation().

Renaming a Torrent path
  • torrent-rename-path

Mapped as TorrentRenamePath().

Session Requests
Session Arguments
  • session-set

Mapped as SessionArgumentsSet().

  • session-get

Mapped as SessionArgumentsGet().

Session Statistics
  • session-stats

Mapped as SessionStats().

Blocklist
  • blocklist-update

Mapped as BlocklistUpdate().

Port Checking
  • port-test

Mapped as PortTest().

Ex:

    st, err := transmissionbt.PortTest()
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
    }
    if st {
        fmt.Println("Open!")
    }
Session Shutdown
  • session-close

Mapped as SessionClose().

Queue Movement Requests
  • queue-move-top

Mapped as QueueMoveTop().

  • queue-move-up

Mapped as QueueMoveUp().

  • queue-move-down

Mapped as QueueMoveDown().

  • queue-move-bottom

Mapped as QueueMoveBottom().

Free Space
  • free-space

Mappped as FreeSpace().

Ex: Get the space available for /data.

    freeSpace, err := transmissionbt.FreeSpace("/data")
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
    } else  {
        fmt.Printd("%s | %d | %v", freeSpace, freeSpace, freeSpace)
    }
}

For more information about the freeSpace type, check the ComputerUnits library.

Documentation

Index

Constants

View Source
const (
	// RPCVersion indicates the exact transmission RPC version this library is build against
	RPCVersion = 15
)

Variables

This section is empty.

Functions

func File2Base64

func File2Base64(filename string) (b64 string, err error)

File2Base64 returns the base64 encoding of the file provided by filename. This can then be passed as MetaInfo in TorrentAddPayload.

Types

type AdvancedConfig

type AdvancedConfig struct {
	HTTPS       bool
	Port        uint16
	RPCURI      string
	HTTPTimeout time.Duration
	UserAgent   string
	Debug       bool
}

AdvancedConfig handles options that are not mandatory for New(). Default value for HTTPS is false, default port is 9091, default RPC URI is '/transmission/rpc', default HTTPTimeout is 30s.

type Client

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

Client is the base object to interract with a remote transmission rpc endpoint. It must be created with New().

func New

func New(host, user, password string, conf *AdvancedConfig) (c *Client, err error)

New returns an initialized and ready to use Controller

func (*Client) BlocklistUpdate

func (c *Client) BlocklistUpdate() (nbEntries int64, err error)

BlocklistUpdate triggers a blocklist update. It returns the number of entries of the updated blocklist.

func (*Client) FreeSpace

func (c *Client) FreeSpace(path string) (freeSpace cunits.Bits, err error)

FreeSpace allow to see how much free space is available in a client-specified folder.

func (*Client) PortTest

func (c *Client) PortTest() (open bool, err error)

PortTest allows tests to see if your incoming peer port is accessible from the outside world.

func (*Client) QueueMoveBottom

func (c *Client) QueueMoveBottom(IDs []int64) (err error)

QueueMoveBottom moves IDs to the bottom of the queue list.

func (*Client) QueueMoveDown

func (c *Client) QueueMoveDown(IDs []int64) (err error)

QueueMoveDown moves IDs of one position down on the queue list.

func (*Client) QueueMoveTop

func (c *Client) QueueMoveTop(IDs []int64) (err error)

QueueMoveTop moves IDs to the top of the queue list.

func (*Client) QueueMoveUp

func (c *Client) QueueMoveUp(IDs []int64) (err error)

QueueMoveUp moves IDs of one position up on the queue list.

func (*Client) RPCVersion

func (c *Client) RPCVersion() (ok bool, serverVersion int64, serverMinimumVersion int64, err error)

RPCVersion returns true if the lib RPC version is greater or equals to the remote server rpc minimum version.

func (*Client) SessionArgumentsGet

func (c *Client) SessionArgumentsGet() (sessionArgs *SessionArguments, err error)

SessionArgumentsGet returns global/session values. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L542

func (*Client) SessionArgumentsSet

func (c *Client) SessionArgumentsSet(payload *SessionArguments) (err error)

SessionArgumentsSet allows to modify global/session values. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L534

func (*Client) SessionClose

func (c *Client) SessionClose() (err error)

SessionClose tells the transmission session to shut down.

func (*Client) SessionStats

func (c *Client) SessionStats() (stats *SessionStats, err error)

SessionStats returns all (current/cumulative) statistics. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L548

func (*Client) TorrentAdd

func (c *Client) TorrentAdd(payload *TorrentAddPayload) (torrent *Torrent, err error)

TorrentAdd allows to send an Add payload. If successful (torrent added or duplicate) torrent return value will only have HashString, ID and Name fields set up. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L373

func (*Client) TorrentAddFile

func (c *Client) TorrentAddFile(filepath string) (torrent *Torrent, err error)

TorrentAddFile is wrapper to directly add a torrent file (it handles the base64 encoding and payload generation). If successful (torrent added or duplicate) torrent return value will only have HashString, ID and Name fields set up.

func (*Client) TorrentAddFileDownloadDir

func (c *Client) TorrentAddFileDownloadDir(filepath, downloaddir string) (torrent *Torrent, err error)

TorrentAddFileDownloadDir is wrapper to directly add a torrent file (it handles the base64 encoding and payload generation) to a DownloadDir (not the default download dir). If successful (torrent added or duplicate) torrent return value will only have HashString, ID and Name fields set up.

func (*Client) TorrentGet

func (c *Client) TorrentGet(fields []string, ids []int64) (torrents []*Torrent, err error)

TorrentGet returns the given of fields (mandatory) for each ids (optionnal). https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L144

func (*Client) TorrentGetAll

func (c *Client) TorrentGetAll() (torrents []*Torrent, err error)

TorrentGetAll returns all the known fields for all the torrents.

func (*Client) TorrentGetAllFor

func (c *Client) TorrentGetAllFor(ids []int64) (torrents []*Torrent, err error)

TorrentGetAllFor returns all known fields for the given torrent's ids.

func (*Client) TorrentGetAllForHashes

func (c *Client) TorrentGetAllForHashes(hashes []string) (torrents []*Torrent, err error)

TorrentGetAllForHashes returns all known fields for the given torrent's ids by string (usually hash).

func (*Client) TorrentGetHashes

func (c *Client) TorrentGetHashes(fields []string, hashes []string) (torrents []*Torrent, err error)

TorrentGetHashes returns the given of fields (mandatory) for each ids (optionnal). https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L144

func (*Client) TorrentReannounceHashes

func (c *Client) TorrentReannounceHashes(hashes []string) (err error)

TorrentReannounceHashes reannounces torrent(s) which hash is in the provided slice. Can be one, can be several, can be all (if slice is empty or nil).

func (*Client) TorrentReannounceIDs

func (c *Client) TorrentReannounceIDs(ids []int64) (err error)

TorrentReannounceIDs reannounces torrent(s) which id is in the provided slice. Can be one, can be several, can be all (if slice is empty or nil).

func (*Client) TorrentReannounceRecentlyActive

func (c *Client) TorrentReannounceRecentlyActive() (err error)

TorrentReannounceRecentlyActive reannounces torrent(s) which have been recently active.

func (*Client) TorrentRemove

func (c *Client) TorrentRemove(payload *TorrentRemovePayload) (err error)

TorrentRemove allows to delete one or more torrents only or with their data.

func (*Client) TorrentRenamePath

func (c *Client) TorrentRenamePath(id int64, path, name string) (err error)

TorrentRenamePath allows to rename torrent name or path. 'path' is the path to the file or folder that will be renamed. 'name' the file or folder's new name https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L440

func (*Client) TorrentRenamePathHash

func (c *Client) TorrentRenamePathHash(hash, path, name string) (err error)

TorrentRenamePathHash allows to rename torrent name or path by its hash. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L440

func (*Client) TorrentSet

func (c *Client) TorrentSet(payload *TorrentSetPayload) (err error)

TorrentSet apply a list of mutator(s) to a list of torrent ids. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L107

func (*Client) TorrentSetLocation

func (c *Client) TorrentSetLocation(id int64, location string, move bool) (err error)

TorrentSetLocation allows to set a new location for one or more torrents. 'location' is the new torrent location. 'move' if true, move from previous location. Otherwise, search "location" for file. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L423

func (*Client) TorrentSetLocationHash

func (c *Client) TorrentSetLocationHash(hash, location string, move bool) (err error)

TorrentSetLocationHash allows to set a new location for one or more torrents. 'location' is the new torrent location. 'move' if true, move from previous location. Otherwise, search "location" for file. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L423

func (*Client) TorrentStartHashes

func (c *Client) TorrentStartHashes(hashes []string) (err error)

TorrentStartHashes starts torrent(s) which hash is in the provided slice. Can be one, can be several, can be all (if slice is empty or nil).

func (*Client) TorrentStartIDs

func (c *Client) TorrentStartIDs(ids []int64) (err error)

TorrentStartIDs starts torrent(s) which id is in the provided slice. Can be one, can be several, can be all (if slice is empty or nil).

func (*Client) TorrentStartNowHashes

func (c *Client) TorrentStartNowHashes(hashes []string) (err error)

TorrentStartNowHashes starts (now) torrent(s) which hash is in the provided slice. Can be one, can be several, can be all (if slice is empty or nil).

func (*Client) TorrentStartNowIDs

func (c *Client) TorrentStartNowIDs(ids []int64) (err error)

TorrentStartNowIDs starts (now) torrent(s) which id is in the provided slice. Can be one, can be several, can be all (if slice is empty or nil).

func (*Client) TorrentStartNowRecentlyActive

func (c *Client) TorrentStartNowRecentlyActive() (err error)

TorrentStartNowRecentlyActive starts (now) torrent(s) which have been recently active.

func (*Client) TorrentStartRecentlyActive

func (c *Client) TorrentStartRecentlyActive() (err error)

TorrentStartRecentlyActive starts torrent(s) which have been recently active.

func (*Client) TorrentStopHashes

func (c *Client) TorrentStopHashes(hashes []string) (err error)

TorrentStopHashes stops torrent(s) which hash is in the provided slice. Can be one, can be several, can be all (if slice is empty or nil).

func (*Client) TorrentStopIDs

func (c *Client) TorrentStopIDs(ids []int64) (err error)

TorrentStopIDs stops torrent(s) which id is in the provided slice. Can be one, can be several, can be all (if slice is empty or nil).

func (*Client) TorrentStopRecentlyActive

func (c *Client) TorrentStopRecentlyActive() (err error)

TorrentStopRecentlyActive stops torrent(s) which have been recently active.

func (*Client) TorrentVerifyHashes

func (c *Client) TorrentVerifyHashes(hashes []string) (err error)

TorrentVerifyHashes verifys torrent(s) which hash is in the provided slice. Can be one, can be several, can be all (if slice is empty or nil).

func (*Client) TorrentVerifyIDs

func (c *Client) TorrentVerifyIDs(ids []int64) (err error)

TorrentVerifyIDs verifys torrent(s) which id is in the provided slice. Can be one, can be several, can be all (if slice is empty or nil).

func (*Client) TorrentVerifyRecentlyActive

func (c *Client) TorrentVerifyRecentlyActive() (err error)

TorrentVerifyRecentlyActive verifys torrent(s) which have been recently active.

type CumulativeStats

type CumulativeStats struct {
	DownloadedBytes int64 `json:"downloadedBytes"`
	FilesAdded      int64 `json:"filesAdded"`
	SecondsActive   int64 `json:"secondsActive"`
	SessionCount    int64 `json:"sessionCount"`
	UploadedBytes   int64 `json:"uploadedBytes"`
}

CumulativeStats is subset of SessionStats. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L562

func (*CumulativeStats) GetDownloaded

func (cs *CumulativeStats) GetDownloaded() (downloaded cunits.Bits)

GetDownloaded returns cumulative stats downloaded size in a handy format

func (*CumulativeStats) GetUploaded

func (cs *CumulativeStats) GetUploaded() (uploaded cunits.Bits)

GetUploaded returns cumulative stats uploaded size in a handy format

type CurrentStats

type CurrentStats struct {
	DownloadedBytes int64 `json:"downloadedBytes"`
	FilesAdded      int64 `json:"filesAdded"`
	SecondsActive   int64 `json:"secondsActive"`
	SessionCount    int64 `json:"sessionCount"`
	UploadedBytes   int64 `json:"uploadedBytes"`
}

CurrentStats is subset of SessionStats. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L570

func (*CurrentStats) GetDownloaded

func (cs *CurrentStats) GetDownloaded() (downloaded cunits.Bits)

GetDownloaded returns current stats downloaded size in a handy format

func (*CurrentStats) GetUploaded

func (cs *CurrentStats) GetUploaded() (uploaded cunits.Bits)

GetUploaded returns current stats uploaded size in a handy format

type Peer

type Peer struct {
	Address              string  `json:"address"`
	ClientName           string  `json:"clientName"`
	ClientIsChoked       bool    `json:"clientIsChoked"`
	ClientIsint64erested bool    `json:"clientIsint64erested"`
	FlagStr              string  `json:"flagStr"`
	IsDownloadingFrom    bool    `json:"isDownloadingFrom"`
	IsEncrypted          bool    `json:"isEncrypted"`
	IsIncoming           bool    `json:"isIncoming"`
	IsUploadingTo        bool    `json:"isUploadingTo"`
	IsUTP                bool    `json:"isUTP"`
	PeerIsChoked         bool    `json:"peerIsChoked"`
	PeerIsint64erested   bool    `json:"peerIsint64erested"`
	Port                 int64   `json:"port"`
	Progress             float64 `json:"progress"`
	RateToClient         int64   `json:"rateToClient"` // B/s
	RateToPeer           int64   `json:"rateToPeer"`   // B/s
}

Peer represent a peer metadata of a torrent's peer list. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L250

func (*Peer) ConvertDownloadSpeed

func (p *Peer) ConvertDownloadSpeed() (speed cunits.Bits)

ConvertDownloadSpeed will return the download speed from peer as cunits.Bits/second

func (*Peer) ConvertUploadSpeed

func (p *Peer) ConvertUploadSpeed() (speed cunits.Bits)

ConvertUploadSpeed will return the upload speed to peer as cunits.Bits/second

type SeedRatioMode

type SeedRatioMode int64

SeedRatioMode represents a torrent current seeding mode

const (
	// SeedRatioModeGlobal represents the use of the global ratio for a torrent
	SeedRatioModeGlobal SeedRatioMode = 0
	// SeedRatioModeCustom represents the use of a custom ratio for a torrent
	SeedRatioModeCustom SeedRatioMode = 1
	// SeedRatioModeNoRatio represents the absence of ratio for a torrent
	SeedRatioModeNoRatio SeedRatioMode = 2
)

func (SeedRatioMode) GoString

func (srm SeedRatioMode) GoString() string

GoString implements the GoStringer interface from the stdlib fmt package

func (SeedRatioMode) String

func (srm SeedRatioMode) String() string

type SessionArguments

type SessionArguments struct {
	AltSpeedDown              *int64   `json:"alt-speed-down"`               // max global download speed (KBps)
	AltSpeedEnabled           *bool    `json:"alt-speed-enabled"`            // true means use the alt speeds
	AltSpeedTimeBegin         *int64   `json:"alt-speed-time-begin"`         // when to turn on alt speeds (units: minutes after midnight)
	AltSpeedTimeEnabled       *bool    `json:"alt-speed-time-enabled"`       // true means the scheduled on/off times are used
	AltSpeedTimeEnd           *int64   `json:"alt-speed-time-end"`           // when to turn off alt speeds (units: same)
	AltSpeedTimeDay           *int64   `json:"alt-speed-time-day"`           // what day(s) to turn on alt speeds (look at tr_sched_day)
	AltSpeedUp                *int64   `json:"alt-speed-up"`                 // max global upload speed (KBps)
	BlocklistURL              *string  `json:"blocklist-url"`                // location of the blocklist to use for "blocklist-update"
	BlocklistEnabled          *bool    `json:"blocklist-enabled"`            // true means enabled
	BlocklistSize             *int64   `json:"blocklist-size"`               // number of rules in the blocklist
	CacheSizeMB               *int64   `json:"cache-size-mb"`                // maximum size of the disk cache (MB)
	ConfigDir                 *string  `json:"config-dir"`                   // location of transmission's configuration directory
	DownloadDir               *string  `json:"download-dir"`                 // default path to download torrents
	DownloadQueueSize         *int64   `json:"download-queue-size"`          // max number of torrents to download at once (see download-queue-enabled)
	DownloadQueueEnabled      *bool    `json:"download-queue-enabled"`       // if true, limit how many torrents can be downloaded at once
	DHTEnabled                *bool    `json:"dht-enabled"`                  // true means allow dht in public torrents
	Encryption                *string  `json:"encryption"`                   // "required", "preferred", "tolerated"
	IdleSeedingLimit          *int64   `json:"idle-seeding-limit"`           // torrents we're seeding will be stopped if they're idle for this long
	IdleSeedingLimitEnabled   *bool    `json:"idle-seeding-limit-enabled"`   // true if the seeding inactivity limit is honored by default
	IncompleteDir             *string  `json:"incomplete-dir"`               // path for incomplete torrents, when enabled
	IncompleteDirEnabled      *bool    `json:"incomplete-dir-enabled"`       // true means keep torrents in incomplete-dir until done
	LPDEnabled                *bool    `json:"lpd-enabled"`                  // true means allow Local Peer Discovery in public torrents
	PeerLimitGlobal           *int64   `json:"peer-limit-global"`            // maximum global number of peers
	PeerLimitPerTorrent       *int64   `json:"peer-limit-per-torrent"`       // maximum global number of peers
	PEXEnabled                *bool    `json:"pex-enabled"`                  // true means allow pex in public torrents
	PeerPort                  *int64   `json:"peer-port"`                    // port number
	PeerPortRandomOnStart     *bool    `json:"peer-port-random-on-start"`    // true means pick a random peer port on launch
	PortForwardingEnabled     *bool    `json:"port-forwarding-enabled"`      // true means enabled
	QueueStalledEnabled       *bool    `json:"queue-stalled-enabled"`        // whether or not to consider idle torrents as stalled
	QueueStalledMinutes       *int64   `json:"queue-stalled-minutes"`        // torrents that are idle for N minuets aren't counted toward seed-queue-size or download-queue-size
	RenamePartialFiles        *bool    `json:"rename-partial-files"`         // true means append ".part" to incomplete files
	RPCVersion                *int64   `json:"rpc-version"`                  // the current RPC API version
	RPCVersionMinimum         *int64   `json:"rpc-version-minimum"`          // the minimum RPC API version supported
	ScriptTorrentDoneFilename *string  `json:"script-torrent-done-filename"` // filename of the script to run
	ScriptTorrentDoneEnabled  *bool    `json:"script-torrent-done-enabled"`  // whether or not to call the "done" script
	SeedRatioLimit            *float64 `json:"seedRatioLimit"`               // the default seed ratio for torrents to use
	SeedRatioLimited          *bool    `json:"seedRatioLimited"`             // true if seedRatioLimit is honored by default
	SeedQueueSize             *int64   `json:"seed-queue-size"`              // max number of torrents to uploaded at once (see seed-queue-enabled)
	SeedQueueEnabled          *bool    `json:"seed-queue-enabled"`           // if true, limit how many torrents can be uploaded at once
	SessionID                 *string  `json:"session-id"`                   // the current session ID
	SpeedLimitDown            *int64   `json:"speed-limit-down"`             // max global download speed (KBps)
	SpeedLimitDownEnabled     *bool    `json:"speed-limit-down-enabled"`     // true means enabled
	SpeedLimitUp              *int64   `json:"speed-limit-up"`               // max global upload speed (KBps)
	SpeedLimitUpEnabled       *bool    `json:"speed-limit-up-enabled"`       // true means enabled
	StartAddedTorrents        *bool    `json:"start-added-torrents"`         // true means added torrents will be started right away
	TrashOriginalTorrentFiles *bool    `json:"trash-original-torrent-files"` // true means the .torrent file of added torrents will be deleted
	Units                     *Units   `json:"units"`                        // see units below
	UTPEnabled                *bool    `json:"utp-enabled"`                  // true means allow utp
	Version                   *string  `json:"version"`                      // long version string "$version ($revision)"
}

SessionArguments represents all the global/session values. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L461

func (*SessionArguments) MarshalJSON

func (sa *SessionArguments) MarshalJSON() (data []byte, err error)

MarshalJSON allows to marshall into JSON only the non nil fields. It differs from 'omitempty' which also skip default values (as 0 or false which can be valid here).

type SessionStats

type SessionStats struct {
	ActiveTorrentCount int64            `json:"activeTorrentCount"`
	CumulativeStats    *CumulativeStats `json:"cumulative-stats"`
	CurrentStats       *CurrentStats    `json:"current-stats"`
	DownloadSpeed      int64            `json:"downloadSpeed"`
	PausedTorrentCount int64            `json:"pausedTorrentCount"`
	TorrentCount       int64            `json:"torrentCount"`
	UploadSpeed        int64            `json:"uploadSpeed"`
}

SessionStats represents all (current/cumulative) statistics. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L554

type Torrent

type Torrent struct {
	ActivityDate            *time.Time         `json:"activityDate"`
	AddedDate               *time.Time         `json:"addedDate"`
	BandwidthPriority       *int64             `json:"bandwidthPriority"`
	Comment                 *string            `json:"comment"`
	CorruptEver             *int64             `json:"corruptEver"`
	Creator                 *string            `json:"creator"`
	DateCreated             *time.Time         `json:"dateCreated"`
	DesiredAvailable        *int64             `json:"desiredAvailable"`
	DoneDate                *time.Time         `json:"doneDate"`
	DownloadDir             *string            `json:"downloadDir"`
	DownloadedEver          *int64             `json:"downloadedEver"`
	DownloadLimit           *int64             `json:"downloadLimit"`
	DownloadLimited         *bool              `json:"downloadLimited"`
	EditDate                *time.Time         `json:"editDate"`
	Error                   *int64             `json:"error"`
	ErrorString             *string            `json:"errorString"`
	Eta                     *int64             `json:"eta"`
	EtaIdle                 *int64             `json:"etaIdle"`
	Files                   []*TorrentFile     `json:"files"`
	FileStats               []*TorrentFileStat `json:"fileStats"`
	HashString              *string            `json:"hashString"`
	HaveUnchecked           *int64             `json:"haveUnchecked"`
	HaveValid               *int64             `json:"haveValid"`
	HonorsSessionLimits     *bool              `json:"honorsSessionLimits"`
	ID                      *int64             `json:"id"`
	IsFinished              *bool              `json:"isFinished"`
	IsPrivate               *bool              `json:"isPrivate"`
	IsStalled               *bool              `json:"isStalled"`
	Labels                  []string           `json:"labels"` // RPC v16
	LeftUntilDone           *int64             `json:"leftUntilDone"`
	MagnetLink              *string            `json:"magnetLink"`
	ManualAnnounceTime      *int64             `json:"manualAnnounceTime"`
	MaxConnectedPeers       *int64             `json:"maxConnectedPeers"`
	MetadataPercentComplete *float64           `json:"metadataPercentComplete"`
	Name                    *string            `json:"name"`
	PeerLimit               *int64             `json:"peer-limit"`
	Peers                   []*Peer            `json:"peers"`
	PeersConnected          *int64             `json:"peersConnected"`
	PeersFrom               *TorrentPeersFrom  `json:"peersFrom"`
	PeersGettingFromUs      *int64             `json:"peersGettingFromUs"`
	PeersSendingToUs        *int64             `json:"peersSendingToUs"`
	PercentDone             *float64           `json:"percentDone"`
	Pieces                  *string            `json:"pieces"` // https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L279
	PieceCount              *int64             `json:"pieceCount"`
	PieceSize               *cunits.Bits       `json:"pieceSize"`
	Priorities              []int64            `json:"priorities"` // https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L285
	QueuePosition           *int64             `json:"queuePosition"`
	RateDownload            *int64             `json:"rateDownload"` // B/s
	RateUpload              *int64             `json:"rateUpload"`   // B/s
	RecheckProgress         *float64           `json:"recheckProgress"`
	SecondsDownloading      *int64             `json:"secondsDownloading"`
	SecondsSeeding          *time.Duration     `json:"secondsSeeding"`
	SeedIdleLimit           *int64             `json:"seedIdleLimit"`
	SeedIdleMode            *int64             `json:"seedIdleMode"`
	SeedRatioLimit          *float64           `json:"seedRatioLimit"`
	SeedRatioMode           *SeedRatioMode     `json:"seedRatioMode"`
	SizeWhenDone            *cunits.Bits       `json:"sizeWhenDone"`
	StartDate               *time.Time         `json:"startDate"`
	Status                  *TorrentStatus     `json:"status"`
	Trackers                []*Tracker         `json:"trackers"`
	TrackerStats            []*TrackerStats    `json:"trackerStats"`
	TotalSize               *cunits.Bits       `json:"totalSize"`
	TorrentFile             *string            `json:"torrentFile"`
	UploadedEver            *int64             `json:"uploadedEver"`
	UploadLimit             *int64             `json:"uploadLimit"`
	UploadLimited           *bool              `json:"uploadLimited"`
	UploadRatio             *float64           `json:"uploadRatio"`
	Wanted                  []bool             `json:"wanted"`   //https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L325
	WebSeeds                []string           `json:"webseeds"` // https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L329
	WebSeedsSendingToUs     *int64             `json:"webseedsSendingToUs"`
}

Torrent represents all the possible fields of data for a torrent. All fields are pointers to detect if the value is nil (field not requested) or default real default value. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L163 https://github.com/transmission/transmission/blob/3.00/extras/rpc-spec.txt#L178

func (*Torrent) ConvertDownloadSpeed

func (t *Torrent) ConvertDownloadSpeed() (speed cunits.Bits)

ConvertDownloadSpeed will return the download speed as cunits.Bitss/second

func (*Torrent) ConvertUploadSpeed

func (t *Torrent) ConvertUploadSpeed() (speed cunits.Bits)

ConvertUploadSpeed will return the upload speed as cunits.Bitss/second

func (*Torrent) MarshalJSON

func (t *Torrent) MarshalJSON() (data []byte, err error)

MarshalJSON allows to convert back golang values to original payload values.

func (*Torrent) UnmarshalJSON

func (t *Torrent) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON allows to convert timestamps to golang time.Time values.

type TorrentAddPayload

type TorrentAddPayload struct {
	Cookies           *string `json:"cookies"`           // pointer to a string of one or more cookies
	DownloadDir       *string `json:"download-dir"`      // path to download the torrent to
	Filename          *string `json:"filename"`          // filename or URL of the .torrent file
	MetaInfo          *string `json:"metainfo"`          // base64-encoded .torrent content
	Paused            *bool   `json:"paused"`            // if true, don't start the torrent
	PeerLimit         *int64  `json:"peer-limit"`        // maximum number of peers
	BandwidthPriority *int64  `json:"bandwidthPriority"` // torrent's bandwidth tr_priority_t
	FilesWanted       []int64 `json:"files-wanted"`      // indices of file(s) to download
	FilesUnwanted     []int64 `json:"files-unwanted"`    // indices of file(s) to not download
	PriorityHigh      []int64 `json:"priority-high"`     // indices of high-priority file(s)
	PriorityLow       []int64 `json:"priority-low"`      // indices of low-priority file(s)
	PriorityNormal    []int64 `json:"priority-normal"`   // indices of normal-priority file(s)
}

TorrentAddPayload represents the data to send in order to add a torrent. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L37762

func (*TorrentAddPayload) MarshalJSON

func (tap *TorrentAddPayload) MarshalJSON() (data []byte, err error)

MarshalJSON allows to marshall into JSON only the non nil fields. It differs from 'omitempty' which also skip default values (as 0 or false which can be valid here).

type TorrentFile

type TorrentFile struct {
	BytesCompleted int64  `json:"bytesCompleted"`
	Length         int64  `json:"length"`
	Name           string `json:"name"`
}

TorrentFile represent one file from a Torrent. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L236

type TorrentFileStat

type TorrentFileStat struct {
	BytesCompleted int64 `json:"bytesCompleted"`
	Wanted         bool  `json:"wanted"`
	Priority       int64 `json:"priority"`
}

TorrentFileStat represents the metadata of a torrent's file. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L242

type TorrentPeersFrom

type TorrentPeersFrom struct {
	FromCache    int64 `json:"fromCache"`
	FromDHT      int64 `json:"fromDht"`
	FromIncoming int64 `json:"fromIncoming"`
	FromLPD      int64 `json:"fromLpd"`
	FromLTEP     int64 `json:"fromLtep"`
	FromPEX      int64 `json:"fromPex"`
	FromTracker  int64 `json:"fromTracker"`
}

TorrentPeersFrom represents the peers statistics of a torrent. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L269

type TorrentRemovePayload

type TorrentRemovePayload struct {
	IDs             []int64 `json:"ids"`
	DeleteLocalData bool    `json:"delete-local-data"`
}

TorrentRemovePayload holds the torrent id(s) to delete with a data deletion flag. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L413

type TorrentSetPayload

type TorrentSetPayload struct {
	BandwidthPriority   *int64         `json:"bandwidthPriority"`   // this torrent's bandwidth tr_priority_t
	DownloadLimit       *int64         `json:"downloadLimit"`       // maximum download speed (KBps)
	DownloadLimited     *bool          `json:"downloadLimited"`     // true if "downloadLimit" is honored
	FilesWanted         []int64        `json:"files-wanted"`        // indices of file(s) to download
	FilesUnwanted       []int64        `json:"files-unwanted"`      // indices of file(s) to not download
	HonorsSessionLimits *bool          `json:"honorsSessionLimits"` // true if session upload limits are honored
	IDs                 []int64        `json:"ids"`                 // torrent list
	Labels              []string       `json:"labels"`              // RPC v16: strings of user-defined labels
	Location            *string        `json:"location"`            // new location of the torrent's content
	PeerLimit           *int64         `json:"peer-limit"`          // maximum number of peers
	PriorityHigh        []int64        `json:"priority-high"`       // indices of high-priority file(s)
	PriorityLow         []int64        `json:"priority-low"`        // indices of low-priority file(s)
	PriorityNormal      []int64        `json:"priority-normal"`     // indices of normal-priority file(s)
	QueuePosition       *int64         `json:"queuePosition"`       // position of this torrent in its queue [0...n)
	SeedIdleLimit       *time.Duration `json:"seedIdleLimit"`       // torrent-level number of minutes of seeding inactivity
	SeedIdleMode        *int64         `json:"seedIdleMode"`        // which seeding inactivity to use
	SeedRatioLimit      *float64       `json:"seedRatioLimit"`      // torrent-level seeding ratio
	SeedRatioMode       *SeedRatioMode `json:"seedRatioMode"`       // which ratio mode to use
	TrackerAdd          []string       `json:"trackerAdd"`          // strings of announce URLs to add
	TrackerRemove       []int64        `json:"trackerRemove"`       // ids of trackers to remove
	TrackerReplace      []string       `json:"trackerReplace"`      // pairs of <trackerId/new announce URLs> (TODO: validate string value usable as is)
	UploadLimit         *int64         `json:"uploadLimit"`         // maximum upload speed (KBps)
	UploadLimited       *bool          `json:"uploadLimited"`       // true if "uploadLimit" is honored
}

TorrentSetPayload contains all the mutators appliable on one torrent. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L111 https://github.com/transmission/transmission/blob/3.00/extras/rpc-spec.txt#L111

func (*TorrentSetPayload) MarshalJSON

func (tsp *TorrentSetPayload) MarshalJSON() (data []byte, err error)

MarshalJSON allows to marshall into JSON only the non nil fields. It differs from 'omitempty' which also skip default values (as 0 or false which can be valid here).

type TorrentStatus

type TorrentStatus int64

TorrentStatus binds torrent status to a status code

const (
	// TorrentStatusStopped represents a stopped torrent
	TorrentStatusStopped TorrentStatus = 0
	// TorrentStatusCheckWait represents a torrent queued for files checking
	TorrentStatusCheckWait TorrentStatus = 1
	// TorrentStatusCheck represents a torrent which files are currently checked
	TorrentStatusCheck TorrentStatus = 2
	// TorrentStatusDownloadWait represents a torrent queue to download
	TorrentStatusDownloadWait TorrentStatus = 3
	// TorrentStatusDownload represents a torrent currently downloading
	TorrentStatusDownload TorrentStatus = 4
	// TorrentStatusSeedWait represents a torrent queued to seed
	TorrentStatusSeedWait TorrentStatus = 5
	// TorrentStatusSeed represents a torrent currently seeding
	TorrentStatusSeed TorrentStatus = 6
	// TorrentStatusIsolated represents a torrent which can't find peers
	TorrentStatusIsolated TorrentStatus = 7
)

func (TorrentStatus) GoString

func (status TorrentStatus) GoString() string

GoString implements the GoStringer interface from the stdlib fmt package

func (TorrentStatus) String

func (status TorrentStatus) String() string

type Tracker

type Tracker struct {
	Announce string `json:"announce"`
	ID       int64  `json:"id"`
	Scrape   string `json:"scrape"`
	Tier     int64  `json:"tier"`
}

Tracker represent the base data of a torrent's tracker. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L289

type TrackerStats

type TrackerStats struct {
	Announce              string    `json:"announce"`
	AnnounceState         int64     `json:"announceState"`
	DownloadCount         int64     `json:"downloadCount"`
	HasAnnounced          bool      `json:"hasAnnounced"`
	HasScraped            bool      `json:"hasScraped"`
	Host                  string    `json:"host"`
	ID                    int64     `json:"id"`
	IsBackup              bool      `json:"isBackup"`
	LastAnnouncePeerCount int64     `json:"lastAnnouncePeerCount"`
	LastAnnounceResult    string    `json:"lastAnnounceResult"`
	LastAnnounceStartTime time.Time `json:"lastAnnounceStartTime"`
	LastAnnounceSucceeded bool      `json:"lastAnnounceSucceeded"`
	LastAnnounceTime      time.Time `json:"lastAnnounceTime"`
	LastAnnounceTimedOut  bool      `json:"lastAnnounceTimedOut"`
	LastScrapeResult      string    `json:"lastScrapeResult"`
	LastScrapeStartTime   time.Time `json:"lastScrapeStartTime"`
	LastScrapeSucceeded   bool      `json:"lastScrapeSucceeded"`
	LastScrapeTime        time.Time `json:"lastScrapeTime"`
	LastScrapeTimedOut    bool      `json:"lastScrapeTimedOut"` // should be boolean but number. Will be converter in UnmarshalJSON
	LeecherCount          int64     `json:"leecherCount"`
	NextAnnounceTime      time.Time `json:"nextAnnounceTime"`
	NextScrapeTime        time.Time `json:"nextScrapeTime"`
	Scrape                string    `json:"scrape"`
	ScrapeState           int64     `json:"scrapeState"`
	SeederCount           int64     `json:"seederCount"`
	Tier                  int64     `json:"tier"`
}

TrackerStats represent the extended data of a torrent's tracker. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L296

func (*TrackerStats) MarshalJSON

func (ts *TrackerStats) MarshalJSON() (data []byte, err error)

MarshalJSON allows to convert back golang values to original payload values.

func (*TrackerStats) UnmarshalJSON

func (ts *TrackerStats) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON allows to convert timestamps to golang time.Time values.

type TransmissionFreeSpace

type TransmissionFreeSpace struct {
	Path string `json:"path"`
	Size int64  `json:"size-bytes"`
}

TransmissionFreeSpace represents the freespace available in bytes for a specific path. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L631

type Units

type Units struct {
	SpeedUnits  []string `json:"speed-units"`  // 4 strings: KB/s, MB/s, GB/s, TB/s
	SpeedBytes  int64    `json:"speed-bytes"`  // number of bytes in a KB (1000 for kB; 1024 for KiB)
	SizeUnits   []string `json:"size-units"`   // 4 strings: KB/s, MB/s, GB/s, TB/s
	SizeBytes   int64    `json:"size-bytes"`   // number of bytes in a KB (1000 for kB; 1024 for KiB)
	MemoryUnits []string `json:"memory-units"` // 4 strings: KB/s, MB/s, GB/s, TB/s
	MemoryBytes int64    `json:"memory-bytes"` // number of bytes in a KB (1000 for kB; 1024 for KiB)
}

Units is subset of SessionArguments. https://github.com/transmission/transmission/blob/2.9x/extras/rpc-spec.txt#L514

func (*Units) GetMemory

func (u *Units) GetMemory() (memory cunits.Bits)

GetMemory returns the memory in a handy format

func (*Units) GetSize

func (u *Units) GetSize() (size cunits.Bits)

GetSize returns the size in a handy format

func (*Units) GetSpeed

func (u *Units) GetSpeed() (speed cunits.Bits)

GetSpeed returns the speed in a handy format

Jump to

Keyboard shortcuts

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