qbt

package module
v1.0.20 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2026 License: GPL-2.0 Imports: 17 Imported by: 0

README

go-qbt - Optimized Go client for qBittorrent

Go Reference Go Report Card Build Go Version Latest Tag

A high-performance Go client for the qBittorrent Web API with advanced optimizations for cookies and retries.

🚀 Key Improvements

  • Cookie cache: Avoids unnecessary validation requests
  • Auto expiration: Cookies are automatically cleared after 24 hours
  • Optimized validation: Verify cookies only when needed
  • Periodic cleanup: Dedicated goroutine to clear expired cookies
2. Advanced Retry System
  • Exponential backoff: Increasing delay between attempts
  • Flexible configuration: Customizable number of retries and delays
  • Smart retry: Only for retryable status codes (408, 429, 500, 502, 503, 504)
  • Detailed logging: Information about attempts and failures
3. Performance Optimizations
  • Configurable timeouts: Per operation and global
  • Context with timeout: Granular control of operations
  • Optimized mutexes: RWMutex for better concurrency
  • Resource management: Automatic cleanup and memory control

📦 Installation

go get github.com/jfxdev/go-qbt

🔧 Configuration

config := qbt.Config{
    BaseURL:        "http://localhost:8080",
    Username:       "admin",
    Password:       "password",
    RequestTimeout: 45 * time.Second,  // Custom timeout
    MaxRetries:     5,                 // Number of attempts
    RetryBackoff:   2 * time.Second,   // Base delay between attempts
    Debug:          false,             // Enable debug logging (default: false)
}
Debug Mode

Enable debug logging to see detailed information about:

  • Login attempts and success
  • Cookie expiration events
  • Retry attempts with delays
  • Operation failures and retries
config := qbt.Config{
    BaseURL:  "http://localhost:8080",
    Username: "admin",
    Password: "password",
    Debug:    true,  // Enable verbose logging
}

Note: In production environments, keep Debug: false to avoid excessive logging.

💻 Basic Usage

// Create client
client, err := qbt.New(config)
if err != nil {
    log.Fatal(err)
}
defer client.Close()

// List torrents (automatic retry and cookie management)
torrents, err := client.ListTorrents(qbt.ListOptions{})
if err != nil {
    log.Printf("Error: %v", err)
}

// Add torrent via magnet link
err = client.AddTorrentLink(qbt.TorrentConfig{
    MagnetURI: "magnet:?xt=urn:btih:...",
    Directory: "/downloads",
    Category:  "movies",
    Paused:    false,
})
if err != nil {
    log.Printf("Error adding torrent: %v", err)
}

🚀 Available Operations

Torrent Management
  • ListTorrents(opts ListOptions) - List all torrents with optional filtering
  • AddTorrentLink(opts TorrentConfig) - Add a torrent via magnet link
  • PauseTorrents(hash string) - Pause specific torrent
  • ResumeTorrents(hash string) - Resume specific torrent
  • DeleteTorrents(hash string, deleteFiles bool) - Delete torrent with optional file deletion
  • IncreaseTorrentsPriority(hash string) - Increase torrent priority
  • DecreaseTorrentsPriority(hash string) - Decrease torrent priority
  • AddTorrentTags(hash string, tags []string) - Add tags to torrent
  • DeleteTorrentTags(hash string, tags []string) - Remove tags from torrent
  • SetCategory(hash string, category string) - Set torrent category
  • RemoveCategory(hash string) - Remove torrent category
  • GetTorrent(hash string) - Get specific torrent information
  • GetTorrentProperties(hash string) - Get detailed torrent properties
  • GetTorrentFiles(hash string) - Get torrent file list
  • GetTorrentTrackers(hash string) - Get torrent tracker information
  • GetTorrentPeers(hash string) - Get torrent peer information
  • ForceRecheck(hash string) - Force torrent recheck
  • ForceReannounce(hash string) - Force torrent reannounce
  • ForceStart(hash string) - Force start torrent
  • SetTorrentDownloadLimit(hash string, limit int) - Set torrent download speed limit
  • SetTorrentUploadLimit(hash string, limit int) - Set torrent upload speed limit
  • SetTorrentShareLimit(hash string, ratioLimit float64, seedingTimeLimit int) - Set torrent share limits
Categories Management
  • GetCategories() - Get all categories
  • CreateCategory(name, savePath string) - Create new category
  • DeleteCategory(name string) - Delete category
Global Settings & Configuration
  • GetGlobalSettings() - Get global qBittorrent settings
  • SetGlobalSettings(settings GlobalSettings) - Set global qBittorrent settings
  • SetDownloadSpeedLimit(limit int) - Set global download speed limit
  • SetUploadSpeedLimit(limit int) - Set global upload speed limit
  • ToggleSpeedLimits() - Toggle speed limits mode
Maximum Active Torrent Management
  • SetMaxActiveDownloads(maxDownloads int) - Set maximum number of active downloads
  • SetMaxActiveUploads(maxUploads int) - Set maximum number of active uploads
  • SetMaxActiveTorrents(maxTorrents int) - Set maximum number of active torrents
  • SetMaxActiveCheckingTorrents(maxChecking int) - Set maximum number of active checking torrents
  • SetMaxActiveTorrentLimits(maxDownloads, maxUploads, maxTorrents, maxChecking int) - Set all maximum active torrent limits at once
  • GetMaxActiveDownloads() - Get current maximum number of active downloads
  • GetMaxActiveUploads() - Get current maximum number of active uploads
  • GetMaxActiveTorrents() - Get current maximum number of active torrents
  • GetMaxActiveCheckingTorrents() - Get current maximum number of active checking torrents
System Information & Monitoring
  • GetMainData() - Get main server data and sync information
  • GetTransferInfo() - Get transfer statistics and information
  • GetNetworkInfo() - Get network information
  • GetAppVersion() - Get qBittorrent application version
  • GetAPIVersion() - Get Web API version
  • GetBuildInfo() - Get build information
  • GetLogs(normal, info, warning, critical bool, lastKnownID int) - Get system logs
RSS Feeds Management
  • GetRSSFeeds(withData bool) - Get RSS feeds
  • AddRSSFeed(url, path string) - Add RSS feed
  • RemoveRSSFeed(path string) - Remove RSS feed

🌱 Essential Features for Seedbox

This SDK has been specially optimized for seedbox usage, including essential features for daily management:

📊 Advanced Monitoring
  • Trackers: Monitor status and performance of all trackers
  • Peers: Track connections, speeds and countries of peers
  • Logs: Access detailed system logs for debugging
  • Network: Monitor network information and DHT connections
⚙️ Speed Control
  • Global Limits: Configure speed limits for download/upload
  • Per-Torrent Limits: Individual speed control per torrent
  • Ratio Management: Configure ratio limits and seeding time
  • Toggle Limits: Quickly enable/disable speed limits
🗂️ Organization and Categorization
  • Categories: Create and manage categories to organize torrents
  • Tags: Add and remove tags for better organization
  • Paths: Configure specific paths per category
🔧 Advanced Settings
  • Global Settings: Access and modify all qBittorrent settings
  • RSS Feeds: Configure RSS feeds for download automation
  • Recheck/Reannounce: Force checks and announcements when needed
💡 Typical Seedbox Use Cases
// Monitor tracker performance
trackers, err := client.GetTorrentTrackers("torrent_hash")
if err != nil {
    log.Printf("Error getting trackers: %v", err)
}

// Configure ratio limit for seeding
err = client.SetTorrentShareLimit("torrent_hash", 2.0, 168) // 2.0 ratio, 168 hours
if err != nil {
    log.Printf("Error configuring ratio: %v", err)
}

// Get system logs for debugging
logs, err := client.GetLogs(true, true, true, true, 0)
if err != nil {
    log.Printf("Error getting logs: %v", err)
}

// Configure category for organization
err = client.CreateCategory("movies", "/downloads/movies")
if err != nil {
    log.Printf("Error creating category: %v", err)
}

⚙️ Advanced Settings

Timeouts
// Global timeout for all operations
config.RequestTimeout = 60 * time.Second
Retries
// Retry configuration
config.MaxRetries = 10            // Max attempts
config.RetryBackoff = 1 * time.Second  // Base delay
Cookies
// Cookie settings are automatic:
// - Expiration: 24 hours
// - Check: every 5 minutes
// - Cache: Smart with automatic invalidation

🔍 Monitoring and Logs

When debug mode is enabled (Debug: true), the client provides detailed logs for:

  • Login attempts and success
  • Failures and retries with attempt counts
  • Cookie expiration events
  • Successful operations after retries

Example debug output:

Login successful, cookies cached
GET /api/v2/torrents/info failed (attempt 1/3), retrying in 2s: authentication error: status code 403
Login successful, cookies cached
GET /api/v2/torrents/info succeeded after 1 retries
Cookies expired, cleared from cache

📊 Performance Metrics

  • Cache hit rate: Cookie cache effectiveness
  • Retry statistics: Attempts and failures
  • Response times: Per operation

🧪 Examples

Maximum Active Torrent Management Example
package main

import (
    "fmt"
    "log"
    "time"
    
    "github.com/jfxdev/go-qbt"
)

func main() {
    config := qbt.Config{
        BaseURL:        "http://localhost:8080",
        Username:       "admin",
        Password:       "password",
        RequestTimeout: 30 * time.Second,
        MaxRetries:     3,
        RetryBackoff:   2 * time.Second,
        Debug:          false,
    }
    
    client, err := qbt.New(config)
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()
    
    // Get current maximum active torrent limits
    maxDownloads, _ := client.GetMaxActiveDownloads()
    maxUploads, _ := client.GetMaxActiveUploads()
    maxTorrents, _ := client.GetMaxActiveTorrents()
    maxChecking, _ := client.GetMaxActiveCheckingTorrents()
    
    fmt.Printf("Current limits - Downloads: %d, Uploads: %d, Torrents: %d, Checking: %d\n",
        maxDownloads, maxUploads, maxTorrents, maxChecking)
    
    // Set individual limits
    err = client.SetMaxActiveDownloads(5)
    if err != nil {
        log.Printf("Error setting max downloads: %v", err)
    }
    
    err = client.SetMaxActiveUploads(3)
    if err != nil {
        log.Printf("Error setting max uploads: %v", err)
    }
    
    // Set all limits at once
    err = client.SetMaxActiveTorrentLimits(8, 4, 15, 2)
    if err != nil {
        log.Printf("Error setting all limits: %v", err)
    } else {
        fmt.Println("Successfully set all maximum active torrent limits")
    }
}
Complete Usage Example
package main

import (
    "fmt"
    "log"
    "time"
    
    "github.com/jfxdev/go-qbt"
)

func main() {
    // Configure client
    config := qbt.Config{
        BaseURL:        "http://localhost:8080",
        Username:       "admin",
        Password:       "password",
        RequestTimeout: 30 * time.Second,
        MaxRetries:     3,
        RetryBackoff:   2 * time.Second,
        Debug:          false, // Set to true for verbose logging
    }
    
    // Create client
    client, err := qbt.New(config)
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()
    
    // Get system information
    version, err := client.GetAppVersion()
    if err != nil {
        log.Printf("Error getting version: %v", err)
    } else {
        fmt.Printf("qBittorrent version: %s\n", version)
    }
    
    // List torrents
    torrents, err := client.ListTorrents(qbt.ListOptions{})
    if err != nil {
        log.Printf("Error listing torrents: %v", err)
        return
    }
    
    fmt.Printf("Found %d torrents\n", len(torrents))
    
    // Add a new torrent
    err = client.AddTorrentLink(qbt.TorrentConfig{
        MagnetURI: "magnet:?xt=urn:btih:...",
        Directory: "/downloads",
        Category:  "movies",
        Paused:    false,
    })
    if err != nil {
        log.Printf("Error adding torrent: %v", err)
    }
    
    // Get transfer info
    info, err := client.GetTransferInfo()
    if err != nil {
        log.Printf("Error getting transfer info: %v", err)
    } else {
        fmt.Printf("Download speed: %d bytes/s\n", info.DlSpeed)
        fmt.Printf("Upload speed: %d bytes/s\n", info.UpSpeed)
    }
}

🔒 Security

  • Secure cookies: Safe session management
  • Timeouts: Prevents hanging operations
  • Validation: Automatic credential verification

🚨 Error Handling

The client implements robust error handling:

  • Automatic retry: For temporary failures with exponential backoff
  • Graceful fallback: Elegant degradation on errors
  • Smart cookie management: Automatic re-authentication when needed
  • Session expiration handling: Detects 401/403 errors and automatically re-authenticates
  • Timeout protection: Prevents hanging operations
Session Expiration Fix

The client now properly handles qBittorrent session timeouts. When the server returns a 403 (Forbidden) or 401 (Unauthorized) error due to an expired session:

  1. The client automatically invalidates the cached cookies
  2. The retry mechanism forces a new login on the next attempt
  3. The operation is retried seamlessly without user intervention

This fixes the issue where, after several hours, the client would continuously return "forbidden" errors because the qBittorrent Web UI session had expired (configured via WebUISessionTimeout in qBittorrent settings), while the client still considered its cached cookies as valid.

📈 Benefits of the Improvements

  1. Lower latency: Cookie cache avoids re-authentication
  2. Higher reliability: Automatic retry on temporary failures
  3. Better performance: Fewer unnecessary requests
  4. Scalability: Supports multiple concurrent operations
  5. Maintainability: Cleaner and more organized code

🤝 Contributing

Contributions are welcome! Please open an issue or pull request.

📄 License

This project is licensed under the GNU General Public License v3.0 - see LICENSE for details.

Documentation

Overview

SPDX-License-Identifier: GPL-3.0-only

Package qbt provides a high-level, production-ready client for the qBittorrent Web API.

Highlights:

  • Smart cookie/session management with in-memory cache and periodic cleanup
  • Automatic retries with exponential backoff for transient failures
  • Configurable timeouts and retry policies
  • Clean, well-typed models for common endpoints

Quick start:

import (
    "log"
    qbt "github.com/jfxdev/go-qbt"
)

func main() {
    client, err := qbt.New(qbt.Config{
        BaseURL:        "http://localhost:8080",
        Username:       "admin",
        Password:       "password",
    })
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    // List all torrents
    _, _ = client.ListTorrents(qbt.ListOptions{})
}

Index

Constants

View Source
const (
	DefaultRequestTimeout = 30 * time.Second
	DefaultMaxRetries     = 3
	DefaultRetryBackoff   = 1 * time.Second
	DefaultMaxDelay       = 30 * time.Second
	DefaultBackoffFactor  = 2.0
	CookieExpiryDuration  = 24 * time.Hour
	CookieCheckInterval   = 5 * time.Minute
)

Default configuration constants

View Source
const (
	StatusConnected    = "connected"
	StatusUnauthorized = "unauthorized"
	StatusUnaccessible = "unaccessible"
	StatusInitializing = "initializing"
	StatusPending      = "pending"
	StatusError        = "error"
)

Variables

This section is empty.

Functions

func IsPermanentError added in v1.0.19

func IsPermanentError(err error) bool

IsPermanentError returns true if the error requires user intervention

func IsRetryableError added in v1.0.19

func IsRetryableError(err error) bool

IsRetryableError returns true if the error is temporary and can be retried

Types

type BuildInfoResponse added in v1.0.10

type BuildInfoResponse struct {
	DlInfoSpeed      int    `json:"dl_info_speed"`
	DlInfoData       int    `json:"dl_info_data"`
	UpInfoSpeed      int    `json:"up_info_speed"`
	UpInfoData       int    `json:"up_info_data"`
	DlRateLimit      int    `json:"dl_rate_limit"`
	UpRateLimit      int    `json:"up_rate_limit"`
	DhtNodes         int    `json:"dht_nodes"`
	ConnectionStatus string `json:"connection_status"`
}

type Category added in v1.0.11

type Category struct {
	Name     string `json:"name"`     // Category name
	SavePath string `json:"savePath"` // Save path for this category
}

Category represents a torrent category

type Client

type Client struct {
	MaxLoginRetries int
	RetryDelay      time.Duration
	// contains filtered or unexported fields
}

Client is a high-level qBittorrent API client with cookie cache and retries.

func New

func New(config Config) (*Client, error)

func (*Client) AddRSSFeed added in v1.0.11

func (qb *Client) AddRSSFeed(feedURL, path string) error

AddRSSFeed adds a new RSS feed

func (qb *Client) AddTorrentLink(opts TorrentConfig) error

func (*Client) AddTorrentTags added in v1.0.3

func (qb *Client) AddTorrentTags(hash string, tags []string) error

func (*Client) Close

func (qb *Client) Close() error

func (*Client) CreateCategory added in v1.0.11

func (qb *Client) CreateCategory(name, savePath string) error

CreateCategory creates a new category

func (*Client) DecreaseTorrentsPriority

func (qb *Client) DecreaseTorrentsPriority(hash string) error

func (*Client) DeleteCategory added in v1.0.11

func (qb *Client) DeleteCategory(name string) error

DeleteCategory removes a category

func (*Client) DeleteTorrentTags added in v1.0.11

func (qb *Client) DeleteTorrentTags(hash string, tags []string) error

func (*Client) DeleteTorrents

func (qb *Client) DeleteTorrents(hash string, deleteFiles bool) error

func (*Client) ForceReannounce added in v1.0.11

func (qb *Client) ForceReannounce(hash string) error

func (*Client) ForceRecheck added in v1.0.11

func (qb *Client) ForceRecheck(hash string) error

func (*Client) ForceStart added in v1.0.11

func (qb *Client) ForceStart(hash string) error

func (*Client) GetAPIVersion added in v1.0.10

func (qb *Client) GetAPIVersion() (string, error)

func (*Client) GetAppVersion added in v1.0.10

func (qb *Client) GetAppVersion() (string, error)

func (*Client) GetBuildInfo added in v1.0.10

func (qb *Client) GetBuildInfo() (*TransferInfoResponse, error)

func (*Client) GetCategories added in v1.0.11

func (qb *Client) GetCategories() (map[string]Category, error)

GetCategories gets all categories

func (*Client) GetConnectionStatus added in v1.0.19

func (qb *Client) GetConnectionStatus() *ConnectionStatus

GetConnectionStatus returns the detailed connection status

func (*Client) GetGlobalDownloadLimit added in v1.0.15

func (qb *Client) GetGlobalDownloadLimit() (int, error)

GetGlobalDownloadLimit gets the global download speed limit

func (*Client) GetGlobalSettings added in v1.0.11

func (qb *Client) GetGlobalSettings() (*GlobalSettings, error)

GetGlobalSettings gets qBittorrent global settings

func (*Client) GetGlobalUploadLimit added in v1.0.15

func (qb *Client) GetGlobalUploadLimit() (int, error)

GetGlobalUploadLimit gets the global upload speed limit

func (*Client) GetLastError added in v1.0.19

func (qb *Client) GetLastError() *ClientError

GetLastError returns the last error that occurred

func (*Client) GetLogs added in v1.0.11

func (qb *Client) GetLogs(normal bool, info bool, warning bool, critical bool, lastKnownID int) ([]*LogEntry, error)

GetLogs gets system logs

func (*Client) GetMainData added in v1.0.7

func (qb *Client) GetMainData() (*MainDataResponse, error)

func (*Client) GetNetworkInfo added in v1.0.11

func (qb *Client) GetNetworkInfo() (*NetworkInfo, error)

GetNetworkInfo gets network information

func (*Client) GetPeerLogs added in v1.0.20

func (qb *Client) GetPeerLogs(lastKnownID int) ([]*PeerLogEntry, error)

GetPeerLogs gets peer logs

func (*Client) GetRSSFeeds added in v1.0.11

func (qb *Client) GetRSSFeeds(withData bool) (map[string]RSSFeed, error)

GetRSSFeeds gets configured RSS feeds

func (*Client) GetStatus added in v1.0.17

func (qb *Client) GetStatus() string

func (*Client) GetTorrent added in v1.0.11

func (qb *Client) GetTorrent(hash string) (*TorrentResponse, error)

func (*Client) GetTorrentDownloadLimit added in v1.0.15

func (qb *Client) GetTorrentDownloadLimit(hash string) (int, error)

GetTorrentDownloadLimit gets download speed limit for a specific torrent

func (*Client) GetTorrentPeers added in v1.0.11

func (qb *Client) GetTorrentPeers(hash string) ([]*TorrentPeer, error)

GetTorrentPeers gets peer information for a torrent

func (*Client) GetTorrentProperties added in v1.0.11

func (qb *Client) GetTorrentProperties(hash string) (*TorrentProperties, error)

func (*Client) GetTorrentTrackers added in v1.0.11

func (qb *Client) GetTorrentTrackers(hash string) ([]*TorrentTracker, error)

GetTorrentTrackers gets tracker information for a torrent

func (*Client) GetTorrentUploadLimit added in v1.0.15

func (qb *Client) GetTorrentUploadLimit(hash string) (int, error)

GetTorrentUploadLimit gets upload speed limit for a specific torrent

func (*Client) GetTransferInfo added in v1.0.8

func (qb *Client) GetTransferInfo() (*TransferInfoResponse, error)

func (*Client) IncreaseTorrentsPriority

func (qb *Client) IncreaseTorrentsPriority(hash string) error

func (*Client) IsAuthFailed added in v1.0.19

func (qb *Client) IsAuthFailed() bool

IsAuthFailed returns true if authentication has permanently failed

func (*Client) ListTorrentFiles added in v1.0.11

func (qb *Client) ListTorrentFiles(hash string) ([]*TorrentFile, error)

func (*Client) ListTorrents

func (qb *Client) ListTorrents(opts ListOptions) ([]*TorrentResponse, error)

func (*Client) RemoveCategory added in v1.0.11

func (qb *Client) RemoveCategory(hash string) error

func (*Client) RemoveRSSFeed added in v1.0.11

func (qb *Client) RemoveRSSFeed(path string) error

RemoveRSSFeed removes an RSS feed

func (*Client) RenameTorrent added in v1.0.13

func (qb *Client) RenameTorrent(hash string, newName string) error

RenameTorrent renames a torrent

func (*Client) ResetAuthFailure added in v1.0.19

func (qb *Client) ResetAuthFailure()

ResetAuthFailure resets the authentication failure flag (call after credential update)

func (*Client) SetAlternativeRateLimits added in v1.0.13

func (qb *Client) SetAlternativeRateLimits(downloadLimit, uploadLimit int) error

SetAlternativeRateLimits sets alternative global download and upload speed limits

func (*Client) SetCategory added in v1.0.11

func (qb *Client) SetCategory(hash string, category string) error

func (*Client) SetGlobalDownloadSpeedLimit added in v1.0.18

func (qb *Client) SetGlobalDownloadSpeedLimit(limit int) error

SetGlobalDownloadSpeedLimit sets the download speed limit

func (*Client) SetGlobalSettings added in v1.0.11

func (qb *Client) SetGlobalSettings(settings GlobalSettings) error

SetGlobalSettings sets qBittorrent global settings

func (*Client) SetGlobalUploadSpeedLimit added in v1.0.18

func (qb *Client) SetGlobalUploadSpeedLimit(limit int) error

SetGlobalUploadSpeedLimit sets the upload speed limit

func (*Client) SetLastError added in v1.0.19

func (qb *Client) SetLastError(err error)

SetLastError stores the last error that occurred

func (*Client) SetMaxActiveTorrentLimits added in v1.0.13

func (qb *Client) SetMaxActiveTorrentLimits(maxDownloads, maxUploads, maxTorrents, maxChecking int) error

SetMaxActiveTorrentLimits sets all maximum active torrent limits at once

func (*Client) SetTorrentDownloadLimit added in v1.0.11

func (qb *Client) SetTorrentDownloadLimit(hash string, limit int) error

SetTorrentDownloadLimit sets download speed limit for a specific torrent

func (*Client) SetTorrentLocation added in v1.0.13

func (qb *Client) SetTorrentLocation(hash string, location string) error

SetTorrentLocation sets the location for torrent files

func (*Client) SetTorrentShareLimit added in v1.0.11

func (qb *Client) SetTorrentShareLimit(hash string, ratioLimit float64, seedingTimeLimit int, inactiveSeedingTimeLimit int) error

SetTorrentShareLimit sets share limits for a specific torrent ratioLimit: -2 means use global limit, -1 means no limit seedingTimeLimit: -2 means use global limit, -1 means no limit (in minutes) inactiveSeedingTimeLimit: -2 means use global limit, -1 means no limit (in minutes)

func (*Client) SetTorrentUploadLimit added in v1.0.11

func (qb *Client) SetTorrentUploadLimit(hash string, limit int) error

SetTorrentUploadLimit sets upload speed limit for a specific torrent

func (*Client) StartTorrent added in v1.0.11

func (qb *Client) StartTorrent(hash string) error

func (*Client) StartTorrents added in v1.0.14

func (qb *Client) StartTorrents(hash string) error

func (*Client) Status added in v1.0.17

func (qb *Client) Status() string

func (*Client) StopTorrent added in v1.0.11

func (qb *Client) StopTorrent(hash string) error

func (*Client) StopTorrents added in v1.0.14

func (qb *Client) StopTorrents(hash string) error

func (*Client) SuperSeedingMode added in v1.0.13

func (qb *Client) SuperSeedingMode(hash string, enabled bool) error

SuperSeedingMode enables or disables super seeding for a torrent

func (*Client) ToggleSpeedLimits added in v1.0.11

func (qb *Client) ToggleSpeedLimits() error

ToggleSpeedLimits toggles speed limits

func (*Client) Update added in v1.0.4

func (qb *Client) Update(config Config)

type ClientError added in v1.0.19

type ClientError struct {
	Code    ErrorCode
	Message string
	Err     error
	// Permanent indicates whether this error requires user intervention (true)
	// or can be resolved by retrying (false)
	Permanent bool
}

ClientError represents a structured error with classification

func ClassifyError added in v1.0.19

func ClassifyError(err error) *ClientError

ClassifyError analyzes an error and returns a structured ClientError

func NewClientError added in v1.0.19

func NewClientError(code ErrorCode, message string, err error, permanent bool) *ClientError

NewClientError creates a new ClientError

func (*ClientError) Error added in v1.0.19

func (e *ClientError) Error() string

func (*ClientError) IsPermanent added in v1.0.19

func (e *ClientError) IsPermanent() bool

IsPermanent returns true if the error requires user intervention

func (*ClientError) Unwrap added in v1.0.19

func (e *ClientError) Unwrap() error

type Config added in v1.0.2

type Config struct {
	BaseURL  string
	Username string
	Password string

	RequestTimeout time.Duration
	MaxRetries     int
	RetryBackoff   time.Duration
	Debug          bool // Enable debug logging for session management
	// contains filtered or unexported fields
}

Config contains runtime client settings and credentials.

type ConnectionStatus added in v1.0.19

type ConnectionStatus struct {
	Status    string    `json:"status"`
	ErrorCode ErrorCode `json:"error_code,omitempty"`
	Message   string    `json:"message,omitempty"`
	Permanent bool      `json:"permanent,omitempty"`
}

ConnectionStatus represents the detailed connection state of the client

type CookieCache added in v1.0.9

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

CookieCache stores session cookies to reduce validation requests.

type ErrorCode added in v1.0.19

type ErrorCode string

ErrorCode represents a specific error type for client-side handling

const (
	// ErrorCodeNone indicates no error
	ErrorCodeNone ErrorCode = ""

	// ErrorCodeAuthFailure indicates invalid username/password - requires user intervention
	ErrorCodeAuthFailure ErrorCode = "AUTH_FAILURE"

	// ErrorCodeTimeout indicates connection or request timeout - temporary, can retry
	ErrorCodeTimeout ErrorCode = "TIMEOUT"

	// ErrorCodeDNS indicates DNS resolution failure - check hostname configuration
	ErrorCodeDNS ErrorCode = "DNS_ERROR"

	// ErrorCodeHTTPSRequired indicates HTTP was used but HTTPS is required
	ErrorCodeHTTPSRequired ErrorCode = "HTTPS_REQUIRED"

	// ErrorCodeSSLError indicates SSL/TLS certificate or connection error
	ErrorCodeSSLError ErrorCode = "SSL_ERROR"

	// ErrorCodeVersionIncompatible indicates incompatible qBittorrent version
	ErrorCodeVersionIncompatible ErrorCode = "VERSION_INCOMPATIBLE"

	// ErrorCodeConnectionRefused indicates the server actively refused the connection
	ErrorCodeConnectionRefused ErrorCode = "CONNECTION_REFUSED"

	// ErrorCodeNetworkUnreachable indicates network routing issues
	ErrorCodeNetworkUnreachable ErrorCode = "NETWORK_UNREACHABLE"

	// ErrorCodeBadGateway indicates a proxy/gateway error (502)
	ErrorCodeBadGateway ErrorCode = "BAD_GATEWAY"

	// ErrorCodeServiceUnavailable indicates the service is temporarily unavailable (503)
	ErrorCodeServiceUnavailable ErrorCode = "SERVICE_UNAVAILABLE"

	// ErrorCodeUnknown indicates an unclassified error
	ErrorCodeUnknown ErrorCode = "UNKNOWN"
)

func GetErrorCode added in v1.0.19

func GetErrorCode(err error) ErrorCode

GetErrorCode extracts the error code from an error

type GlobalSettings added in v1.0.11

type GlobalSettings struct {
	Locale                             string  `json:"locale"`                                 // Interface language
	CreateSubfolderEnabled             bool    `json:"create_subfolder_enabled"`               // Create subfolder
	StartPausedEnabled                 bool    `json:"start_paused_enabled"`                   // Start paused
	AutoDeleteMode                     int     `json:"auto_delete_mode"`                       // Auto delete mode
	SavePath                           string  `json:"save_path"`                              // Default save path
	MaxRatioEnabled                    bool    `json:"max_ratio_enabled"`                      // Max ratio enabled
	MaxRatio                           float64 `json:"max_ratio"`                              // Max ratio
	MaxRatioAct                        int     `json:"max_ratio_act"`                          // Max ratio action
	ListenPort                         int     `json:"listen_port"`                            // Listen port
	MaxActiveTorrents                  int     `json:"max_active_torrents"`                    // Max active torrents
	MaxActiveDownloads                 int     `json:"max_active_downloads"`                   // Max active downloads
	MaxActiveUploads                   int     `json:"max_active_uploads"`                     // Max active uploads
	MaxActiveCheckingTorrents          int     `json:"max_active_checking_torrents"`           // Max active checking torrents
	AlternativeGlobalSpeedLimit        int     `json:"alternative_global_speed_limit"`         // Alternative global speed limit
	AlternativeGlobalSpeedLimitEnabled bool    `json:"alternative_global_speed_limit_enabled"` // Alternative global speed limit enabled
	GlobalSpeedLimit                   int     `json:"global_speed_limit"`                     // Global speed limit
	GlobalSpeedLimitEnabled            bool    `json:"global_speed_limit_enabled"`             // Global speed limit enabled
	AltGlobalSpeedLimit                int     `json:"alt_global_speed_limit"`                 // Alt global speed limit
	AltGlobalSpeedLimitEnabled         bool    `json:"alt_global_speed_limit_enabled"`         // Alt global speed limit enabled
	GlobalDLSpeedLimit                 int     `json:"global_dl_speed_limit"`                  // Global download speed limit
	GlobalDLSpeedLimitEnabled          bool    `json:"global_dl_speed_limit_enabled"`          // Global download speed limit enabled
	GlobalUPSpeedLimit                 int     `json:"global_up_speed_limit"`                  // Global upload speed limit
	GlobalUPSpeedLimitEnabled          bool    `json:"global_up_speed_limit_enabled"`          // Global upload speed limit enabled
}

GlobalSettings represents qBittorrent global settings

type ListFilter

type ListFilter struct {
	Category string
}

ListFilter is deprecated; use ListOptions instead.

type ListOptions

type ListOptions struct {
	Category string
}

ListOptions filters listing endpoints.

type LogEntry added in v1.0.11

type LogEntry struct {
	ID        int    `json:"id"`        // Log entry ID
	Message   string `json:"message"`   // Log message
	Timestamp int64  `json:"timestamp"` // Timestamp
	Type      int    `json:"type"`      // Log type (normal=1, info=2, warning=4, critical=8)
}

LogEntry represents a log entry

type MagnetLink struct {
	Hash             string   `json:"hash"`              // Hash of the torrent (btih)
	DisplayName      string   `json:"display_name"`      // File/torrent name (dn)
	Trackers         []string `json:"trackers"`          // List of trackers (tr)
	ExactLength      string   `json:"exact_length"`      // Exact length (xl)
	ExactSource      string   `json:"exact_source"`      // Exact source (xs)
	Keywords         string   `json:"keywords"`          // Keywords (kt)
	AcceptableSource string   `json:"acceptable_source"` // Acceptable source (as)
}

MagnetLink represents the data extracted from a magnet link

func ParseMagnetLink(magnetURI string) (*MagnetLink, error)

ParseMagnetLink extracts information from a magnet link

type MainDataResponse added in v1.0.7

type MainDataResponse struct {
	ServerState MainDataServerStateResponse `json:"server_state"`
}

MainDataResponse represents a subset of sync/maindata response.

type MainDataServerStateResponse added in v1.0.7

type MainDataServerStateResponse struct {
	FreeSpaceOnDisk       int    `json:"free_space_on_disk"`
	AllTimeDownloaded     int    `json:"alltime_dl"`
	AllTimeUploaded       int    `json:"alltime_ul"`
	ConnectionStatus      string `json:"connection_status"`
	GlobalRatio           string `json:"global_ratio"`
	LastExternalAddressV4 string `json:"last_external_address_v4"`
	LastExternalAddressV6 string `json:"last_external_address_v6"`
}

MainDataServerStateResponse contains server metrics.

type NetworkInfo added in v1.0.11

type NetworkInfo struct {
	ConnectionStatus string `json:"connection_status"` // Connection status
	DhtNodes         int    `json:"dht_nodes"`         // DHT nodes
	DlInfoData       int64  `json:"dl_info_data"`      // Downloaded data
	DlInfoSpeed      int    `json:"dl_info_speed"`     // Download speed
	DlRateLimit      int    `json:"dl_rate_limit"`     // Download rate limit
	UpInfoData       int64  `json:"up_info_data"`      // Uploaded data
	UpInfoSpeed      int    `json:"up_info_speed"`     // Upload speed
	UpRateLimit      int    `json:"up_rate_limit"`     // Upload rate limit
}

NetworkInfo represents network information

type PeerLogEntry added in v1.0.20

type PeerLogEntry struct {
	ID        int    `json:"id"`        // Log entry ID
	IP        string `json:"ip"`        // IP address
	Timestamp int64  `json:"timestamp"` // Timestamp
	Blocked   bool   `json:"blocked"`   // Whether the peer was blocked
	Reason    string `json:"reason"`    // Reason for blocking
}

PeerLogEntry represents a peer log entry

type RSSArticle added in v1.0.11

type RSSArticle struct {
	ID          string `json:"id"`          // Article ID
	Title       string `json:"title"`       // Article title
	Summary     string `json:"summary"`     // Article summary
	Link        string `json:"link"`        // Article link
	IsRead      bool   `json:"isRead"`      // Is read
	Date        string `json:"date"`        // Article date
	Description string `json:"description"` // Article description
	TorrentURL  string `json:"torrentURL"`  // Torrent URL
	Size        int64  `json:"size"`        // File size
}

RSSArticle represents an RSS article

type RSSFeed added in v1.0.11

type RSSFeed struct {
	URL       string       `json:"url"`       // Feed URL
	Title     string       `json:"title"`     // Feed title
	LastBuild string       `json:"lastBuild"` // Last build date
	IsLoading bool         `json:"isLoading"` // Is loading
	HasError  bool         `json:"hasError"`  // Has error
	Articles  []RSSArticle `json:"articles"`  // Articles
}

RSSFeed represents an RSS feed

type RetryConfig added in v1.0.9

type RetryConfig struct {
	MaxRetries     int
	BaseDelay      time.Duration
	MaxDelay       time.Duration
	BackoffFactor  float64
	RetryableCodes []int
}

RetryConfig configures retry behavior and backoff parameters.

type TorrentConfig

type TorrentConfig struct {
	MagnetURI    string
	Directory    string
	Category     string
	Paused       bool
	SkipChecking bool
}

TorrentConfig configures new torrent creation.

type TorrentFile added in v1.0.11

type TorrentFile struct {
	Name         string  `json:"name"`         // File name
	Size         int64   `json:"size"`         // File size in bytes
	Progress     float64 `json:"progress"`     // Download progress (0.0 to 1.0)
	Priority     int     `json:"priority"`     // File priority
	IsSeed       bool    `json:"is_seed"`      // Whether the file is seeded
	PieceRange   [2]int  `json:"piece_range"`  // Piece range [start, end]
	Availability float64 `json:"availability"` // File availability (0.0 to 1.0)
}

TorrentFile represents a file within a torrent

type TorrentPeer added in v1.0.11

type TorrentPeer struct {
	IP            string  `json:"ip"`           // Peer IP address
	Port          int     `json:"port"`         // Peer port
	Client        string  `json:"client"`       // Client name
	Flags         string  `json:"flags"`        // Peer flags
	FlagsDesc     string  `json:"flags_desc"`   // Flags description
	Connection    string  `json:"connection"`   // Connection type
	Country       string  `json:"country"`      // Country code
	CountryCode   string  `json:"country_code"` // Country code
	Downloaded    int64   `json:"downloaded"`   // Downloaded bytes
	DownloadSpeed int     `json:"dl_speed"`     // Download speed
	Files         string  `json:"files"`        // Files
	Progress      float64 `json:"progress"`     // Progress (0.0 to 1.0)
	Relevance     int     `json:"relevance"`    // Relevance
	Uploaded      int64   `json:"uploaded"`     // Uploaded bytes
	UploadSpeed   int     `json:"up_speed"`     // Upload speed
}

TorrentPeer represents peer information

type TorrentProperties added in v1.0.11

type TorrentProperties struct {
	SavePath                 string  `json:"save_path"`                   // Save path
	CreationDate             int64   `json:"creation_date"`               // Creation date
	PieceSize                int64   `json:"piece_size"`                  // Piece size
	Comment                  string  `json:"comment"`                     // Comment
	TotalWasted              int64   `json:"total_wasted"`                // Total wasted
	TotalUploaded            int64   `json:"total_uploaded"`              // Total uploaded
	TotalDownloaded          int64   `json:"total_downloaded"`            // Total downloaded
	UpLimit                  int     `json:"up_limit"`                    // Upload limit
	DlLimit                  int     `json:"dl_limit"`                    // Download limit
	TimeElapsed              int     `json:"time_elapsed"`                // Time elapsed
	SeedingTime              int     `json:"seeding_time"`                // Seeding time
	NbConnections            int     `json:"nb_connections"`              // Number of connections
	NbConnectionsLimit       int     `json:"nb_connections_limit"`        // Number of connections limit
	ShareRatio               float64 `json:"share_ratio"`                 // Share ratio
	AdditionDate             int64   `json:"addition_date"`               // Addition date
	CompletionDate           int64   `json:"completion_date"`             // Completion date
	CreatedBy                string  `json:"created_by"`                  // Created by
	DlSpeedAvg               int     `json:"dl_speed_avg"`                // Download speed average
	DlSpeed                  int     `json:"dl_speed"`                    // Download speed
	Eta                      int     `json:"eta"`                         // ETA
	LastSeen                 int     `json:"last_seen"`                   // Last seen
	Peers                    int     `json:"peers"`                       // Peers
	PeersTotal               int     `json:"peers_total"`                 // Total peers
	PiecesHave               int     `json:"pieces_have"`                 // Pieces have
	PiecesNum                int     `json:"pieces_num"`                  // Total pieces
	Reannounce               int     `json:"reannounce"`                  // Reannounce
	Seeds                    int     `json:"seeds"`                       // Seeds
	SeedsTotal               int     `json:"seeds_total"`                 // Total seeds
	ShareLimit               int     `json:"share_limit"`                 // Share limit (deprecated, use specific limits below)
	RatioLimit               float64 `json:"ratio_limit"`                 // Ratio limit (-2 = use global, -1 = no limit)
	MaxRatio                 float64 `json:"max_ratio"`                   // Max ratio (alternative field name, same as ratio_limit)
	SeedingTimeLimit         int     `json:"seeding_time_limit"`          // Seeding time limit in minutes (-2 = use global, -1 = no limit)
	MaxSeedingTime           int     `json:"max_seeding_time"`            // Max seeding time (alternative field name, same as seeding_time_limit)
	InactiveSeedingTimeLimit int     `json:"inactive_seeding_time_limit"` // Inactive seeding time limit in minutes (-2 = use global, -1 = no limit)
	UpSpeedAvg               int     `json:"up_speed_avg"`                // Upload speed average
	UpSpeed                  int     `json:"up_speed"`                    // Upload speed
}

TorrentProperties represents detailed properties of a torrent

type TorrentResponse added in v1.0.7

type TorrentResponse struct {
	AddedOn                  int         `json:"added_on"`
	Category                 string      `json:"category"`
	CompletionOn             int64       `json:"completion_on"`
	Dlspeed                  int         `json:"dlspeed"`
	Downloaded               int         `json:"downloaded"`
	Eta                      int         `json:"eta"`
	ForceStart               bool        `json:"force_start"`
	Hash                     string      `json:"hash"`
	InfoHashV1               string      `json:"infohash_v1"`
	InfoHashV2               string      `json:"infohash_v2"`
	MagnetURI                string      `json:"magnet_uri"`
	MagnetLink               *MagnetLink `json:"magnet_link"`
	Name                     string      `json:"name"`
	NumComplete              int         `json:"num_complete"`
	NumIncomplete            int         `json:"num_incomplete"`
	NumLeechs                int         `json:"num_leechs"`
	NumSeeds                 int         `json:"num_seeds"`
	Popularity               float64     `json:"popularity"`
	Priority                 int         `json:"priority"`
	Progress                 float64     `json:"progress"`
	Ratio                    float64     `json:"ratio"`
	SavePath                 string      `json:"save_path"`
	SeqDl                    bool        `json:"seq_dl"`
	Size                     int         `json:"size"`
	State                    string      `json:"state"`
	SuperSeeding             bool        `json:"super_seeding"`
	Upspeed                  int         `json:"upspeed"`
	Uploaded                 int         `json:"uploaded"`
	Tags                     string      `json:"tags"`
	RatioLimit               float64     `json:"ratio_limit"`                 // Ratio limit (-2 = use global, -1 = no limit)
	MaxRatio                 float64     `json:"max_ratio"`                   // Max ratio (alternative field name)
	SeedingTimeLimit         int         `json:"seeding_time_limit"`          // Seeding time limit in minutes
	MaxSeedingTime           int         `json:"max_seeding_time"`            // Max seeding time (alternative field name)
	InactiveSeedingTimeLimit int         `json:"inactive_seeding_time_limit"` // Inactive seeding time limit in minutes
}

TorrentResponse is a subset of torrent info returned by qBittorrent.

type TorrentTracker added in v1.0.11

type TorrentTracker struct {
	URL           string `json:"url"`            // Tracker URL
	Status        int    `json:"status"`         // Tracker status
	Tier          int    `json:"tier"`           // Tracker tier
	NumPeers      int    `json:"num_peers"`      // Number of peers
	NumSeeds      int    `json:"num_seeds"`      // Number of seeds
	NumLeeches    int    `json:"num_leeches"`    // Number of leeches
	NumDownloaded int    `json:"num_downloaded"` // Number of downloads
	Msg           string `json:"msg"`            // Tracker message
}

TorrentTracker represents tracker information

type TransferInfoResponse added in v1.0.8

type TransferInfoResponse struct {
	DlInfoSpeed      int    `json:"dl_info_speed"`
	DlInfoData       int    `json:"dl_info_data"`
	UpInfoSpeed      int    `json:"up_info_speed"`
	UpInfoData       int    `json:"up_info_data"`
	DlRateLimit      int    `json:"dl_rate_limit"`
	UpRateLimit      int    `json:"up_rate_limit"`
	DhtNodes         int    `json:"dht_nodes"`
	ConnectionStatus string `json:"connection_status"`
}

TransferInfoResponse represents global transfer information.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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