qbittorrent

package module
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Jan 11, 2025 License: MIT Imports: 10 Imported by: 0

README

qBittorrent Go Client Library

A Go client library for interacting with the qBittorrent Web API.

Features

  • Authentication: Log in to the qBittorrent Web API.
  • Torrent Management:
    • Add new torrents.
    • Delete existing torrents.
    • Export torrent files.
    • Retrieve torrent information.
    • Manage torrent force-start settings.
  • Tracker Information: Fetch tracker details for specific torrents.

Installation

To install the package, run:

go get github.com/cehbz/qbittorrent

Usage

Importing the Package
import (
    "github.com/cehbz/qbittorrent"
)
Initializing the Client
client, err := qbittorrent.NewClient("username", "password", "localhost", "8080")
if err != nil {
    log.Fatalf("Failed to create client: %v", err)
}
  • username: Your qBittorrent Web UI username. Empty if none.
  • password: Your qBittorrent Web UI password. Empty if none.
  • addr: The address where qBittorrent is running (e.g., "127.0.0.1").
  • port: The port number of the qBittorrent Web UI (e.g., "8080").
Adding a Torrent
torrentData, err := os.ReadFile("path/to/your.torrent")
if err != nil {
    log.Fatalf("Failed to read torrent file: %v", err)
}

err = client.TorrentsAdd("your.torrent", torrentData)
if err != nil {
    log.Fatalf("Failed to add torrent: %v", err)
}
Deleting a Torrent
err := client.TorrentsDelete("torrent-hash")
if err != nil {
    log.Fatalf("Failed to delete torrent: %v", err)
}
Exporting a Torrent File
data, err := client.TorrentsExport("torrent-hash")
if err != nil {
    log.Fatalf("Failed to export torrent: %v", err)
}

err = os.WriteFile("exported.torrent", data, 0644)
if err != nil {
    log.Fatalf("Failed to write exported torrent file: %v", err)
}
Retrieving Torrent Information
torrents, err := client.TorrentsInfo()
if err != nil {
    log.Fatalf("Failed to retrieve torrents info: %v", err)
}

for _, torrent := range torrents {
    fmt.Printf("Name: %s, Progress: %.2f%%
", torrent.Name, torrent.Progress*100)
}
Fetching Tracker Information
trackers, err := client.TorrentsTrackers("torrent-hash")
if err != nil {
    log.Fatalf("Failed to get trackers: %v", err)
}

for _, tracker := range trackers {
    fmt.Printf("URL: %s, Status: %d
", tracker.URL, tracker.Status)
}

License

This project is licensed under the MIT License - see the LICENSE file for details.

Contribution

Contributions are welcome! Please open an issue or submit a pull request for any improvements or bug fixes.

Acknowledgments

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Category

type Category map[string]interface{} // no idea what this should be, category=CategoryName&savePath=/path/to/dir

type Client

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

Client is used to interact with the qBittorrent API

func NewClient

func NewClient(username, password, addr, port string, httpClient ...*http.Client) (*Client, error)

NewClient initializes a new qBittorrent client. If httpClient is nil, http.DefaultClient is used.

func (*Client) AuthLogin

func (c *Client) AuthLogin() error

AuthLogin logs in to the qBittorrent Web API

func (*Client) SetForceStart

func (c *Client) SetForceStart(hash string, value bool) error

SetForceStart enables force start for the torrent

func (*Client) SyncMainData

func (c *Client) SyncMainData(rid int) (*MainData, error)

func (*Client) SyncTorrentPeers

func (c *Client) SyncTorrentPeers(hash string, rid int) (*TorrentPeers, error)

func (*Client) TorrentsAdd

func (c *Client) TorrentsAdd(torrentFile string, fileData []byte) error

TorrentsAdd adds a torrent to qBittorrent via Web API using multipart/form-data

func (*Client) TorrentsAddTags

func (c *Client) TorrentsAddTags(hashes, tags string) error

TorrentsAddTags adds tags to the specified torrents

func (*Client) TorrentsAddWithOptions

func (c *Client) TorrentsAddWithOptions(torrentFile string, fileData []byte, opts ...TorrentAddOption) error

func (*Client) TorrentsCreateTags

func (c *Client) TorrentsCreateTags(tags string) error

TorrentsCreateTags creates new tags in qBittorrent

func (*Client) TorrentsDelete

func (c *Client) TorrentsDelete(infohash string) error

TorrentsDelete deletes a torrent from qBittorrent by its hash

func (*Client) TorrentsDeleteTags

func (c *Client) TorrentsDeleteTags(tags string) error

TorrentsDeleteTags deletes tags from qBittorrent

func (*Client) TorrentsDownload

func (c *Client) TorrentsDownload(infohash string) ([]byte, error)

TorrentsDownload retrieves the torrent file by its hash from the qBittorrent server

func (*Client) TorrentsExport

func (c *Client) TorrentsExport(hash string) ([]byte, error)

TorrentsExport retrieves the .torrent file for a given torrent hash

func (*Client) TorrentsGetAllTags

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

TorrentsGetAllTags retrieves all tags from qBittorrent

func (*Client) TorrentsGetTags

func (c *Client) TorrentsGetTags(hashes string) ([]string, error)

TorrentsGetTags retrieves the tags for the given torrent hashes

func (*Client) TorrentsInfo

func (c *Client) TorrentsInfo(params ...*TorrentsInfoParams) ([]TorrentInfo, error)

TorrentsInfo retrieves a list of all torrents from the qBittorrent server

func (*Client) TorrentsRemoveTags

func (c *Client) TorrentsRemoveTags(hashes, tags string) error

TorrentsRemoveTags removes tags from the specified torrents

func (*Client) TorrentsTrackers

func (c *Client) TorrentsTrackers(hash string) ([]TrackerInfo, error)

TorrentsTrackers retrieves the tracker info for a given torrent hash

type InfoHash

type InfoHash string

type MainData

type MainData struct {
	Categories        map[string]Category    `json:"categories"`
	CategoriesRemoved []Category             `json:"categories_removed"`
	FullUpdate        bool                   `json:"full_update"`
	Rid               int                    `json:"rid"`
	ServerState       ServerState            `json:"server_state"`
	Tags              []string               `json:"tags"`
	TagsRemoved       []string               `json:"tags_removed"`
	Torrents          map[string]TorrentInfo `json:"torrents"`
	TorrentsRemoved   []string               `json:"torrents_removed"`
	Trackers          map[string][]InfoHash  `json:"trackers"` // maps trackers to infohashes
}

fields might be missing, in which case we need to switch to pointers and allow "omitempty" https://github.com/qbittorrent/qBittorrent/blob/master/src/base/json_api.cpp#L101 MainData is the data returned by the /api/v2/sync/maindata endpoint

type ServerState

type ServerState struct {
	AllTimeDL            int64  `json:"alltime_dl"`
	AllTimeUL            int64  `json:"alltime_ul"`
	AverageTimeQueue     int    `json:"average_time_queue"`
	ConnectionStatus     string `json:"connection_status"`
	DHTNodes             int    `json:"dht_nodes"`
	DLInfoData           int64  `json:"dl_info_data"`
	DLInfoSpeed          int    `json:"dl_info_speed"`
	DLRateLimit          int    `json:"dl_rate_limit"`
	FreeSpaceOnDisk      int64  `json:"free_space_on_disk"`
	GlobalRatio          string `json:"global_ratio"`
	QueuedIOJobs         int    `json:"queued_io_jobs"`
	Queueing             bool   `json:"queueing"`
	ReadCacheHits        string `json:"read_cache_hits"`
	ReadCacheOverload    string `json:"read_cache_overload"`
	RefreshInterval      int    `json:"refresh_interval"`
	TotalBuffersSize     int64  `json:"total_buffers_size"`
	TotalPeerConnections int    `json:"total_peer_connections"`
	TotalQueuedSize      int64  `json:"total_queued_size"`
	TotalWastedSession   int64  `json:"total_wasted_session"`
	UpInfoData           int64  `json:"up_info_data"`
	UpInfoSpeed          int    `json:"up_info_speed"`
	UpRateLimit          int    `json:"up_rate_limit"`
	UseAltSpeedLimits    bool   `json:"use_alt_speed_limits"`
	UseSubcategories     bool   `json:"use_subcategories"`
	WriteCacheOverload   string `json:"write_cache_overload"`
}

type TorrentAddOption

type TorrentAddOption func(*TorrentsAddOptions)

func WithAutoTMM added in v1.1.1

func WithAutoTMM(autoTMM bool) TorrentAddOption

func WithCategory added in v1.1.1

func WithCategory(category string) TorrentAddOption

func WithSavePath added in v1.1.1

func WithSavePath(savePath string) TorrentAddOption

func WithSkipChecking added in v1.1.2

func WithSkipChecking(skipChecking bool) TorrentAddOption

func WithStartPaused added in v1.1.1

func WithStartPaused(startPaused bool) TorrentAddOption

func WithTags added in v1.1.1

func WithTags(tags []string) TorrentAddOption

type TorrentInfo

type TorrentInfo struct {
	AddedOn            int64    `json:"added_on"`
	AmountLeft         int64    `json:"amount_left"`
	AutoTMM            bool     `json:"auto_tmm"`
	Availability       float64  `json:"availability"`
	Category           string   `json:"category"`
	Completed          int64    `json:"completed"`
	CompletionOn       int64    `json:"completion_on"`
	ContentPath        string   `json:"content_path"`
	DLLimit            int64    `json:"dl_limit"`
	DLSpeed            int64    `json:"dlspeed"`
	Downloaded         int64    `json:"downloaded"`
	DownloadedSession  int64    `json:"downloaded_session"`
	ETA                int64    `json:"eta"`
	FirstLastPiecePrio bool     `json:"f_l_piece_prio"`
	ForceStart         bool     `json:"force_start"`
	Hash               InfoHash `json:"hash"`
	IsPrivate          bool     `json:"isPrivate"`
	LastActivity       int64    `json:"last_activity"`
	MagnetURI          string   `json:"magnet_uri"`
	MaxRatio           float64  `json:"max_ratio"`
	MaxSeedingTime     int64    `json:"max_seeding_time"`
	Name               string   `json:"name"`
	NumComplete        int64    `json:"num_complete"`
	NumIncomplete      int64    `json:"num_incomplete"`
	NumLeechs          int64    `json:"num_leechs"`
	NumSeeds           int64    `json:"num_seeds"`
	Priority           int64    `json:"priority"`
	Progress           float64  `json:"progress"`
	Ratio              float64  `json:"ratio"`
	RatioLimit         float64  `json:"ratio_limit"`
	SavePath           string   `json:"save_path"`
	SeedingTime        int64    `json:"seeding_time"`
	SeedingTimeLimit   int64    `json:"seeding_time_limit"`
	SeenComplete       int64    `json:"seen_complete"`
	SequentialDownload bool     `json:"seq_dl"`
	Size               int64    `json:"size"`
	State              string   `json:"state"`
	SuperSeeding       bool     `json:"super_seeding"`
	Tags               []string `json:"-"`
	TimeActive         int64    `json:"time_active"`
	TotalSize          int64    `json:"total_size"`
	Tracker            string   `json:"tracker"`
	UpLimit            int64    `json:"up_limit"`
	Uploaded           int64    `json:"uploaded"`
	UploadedSession    int64    `json:"uploaded_session"`
	UpSpeed            int64    `json:"upspeed"`
}

TorrentInfo represents the structured information of a torrent from the qBittorrent API

func (*TorrentInfo) UnmarshalJSON

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

UnmarshalJSON custom unmarshaller for TorrentInfo to handle Tags

type TorrentPeer

type TorrentPeer struct {
	Client       string  `json:"client"`
	Connection   string  `json:"connection"`
	Country      string  `json:"country"`
	CountryCode  string  `json:"country_code"`
	DLSpeed      int64   `json:"dl_speed"`
	Downloaded   int64   `json:"downloaded"`
	Files        string  `json:"files"`
	Flags        string  `json:"flags"`
	FlagsDesc    string  `json:"flags_desc"`
	IP           string  `json:"ip"`
	PeerIDClient string  `json:"peer_id_client"`
	Port         int     `json:"port"`
	Progress     float64 `json:"progress"`
	Relevance    float64 `json:"relevance"`
	Uploaded     int64   `json:"uploaded"`
	UPSpeed      int64   `json:"up_speed"`
}

type TorrentPeers

type TorrentPeers struct {
	FullUpdate bool                   `json:"full_update"`
	Peers      map[string]TorrentPeer `json:"peers"`
	// PeersRemoved map[string][]string    `json:"peers_removed"`
	Rid       int  `json:"rid"`
	ShowFlags bool `json:"show_flags"`
}

type TorrentsAddOptions

type TorrentsAddOptions struct {
	SkipChecking *bool
	SavePath     *string
	Category     *string
	Tags         *[]string
	StartPaused  *bool
	AutoTMM      *bool
}

These are not all the options, just the ones i need documentation at: https://github.com/qbittorrent/qBittorrent/wiki/WebUI-API-(qBittorrent-4.1)#add-new-torrent

type TorrentsInfoParams

type TorrentsInfoParams struct {
	Filter   string
	Category string
	Tag      string
	Sort     string
	Reverse  bool
	Limit    int
	Offset   int
	Hashes   []string
}

TorrentsInfoParams holds the optional parameters for the TorrentsInfo method

type TrackerInfo

type TrackerInfo struct {
	URL      string `json:"url"`
	Status   int    `json:"status"`
	Tier     int    `json:"tier"`
	NumPeers int    `json:"num_peers"`
	Msg      string `json:"msg"`
}

TrackerInfo represents a tracker info for a torrent

Jump to

Keyboard shortcuts

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