downloader

package
v0.31.1 Latest Latest
Warning

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

Go to latest
Published: May 16, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrAuthenticationFailed = errors.New("authentication failed")
	ErrConnectionFailed     = errors.New("connection failed")
	ErrTorrentNotFound      = errors.New("torrent not found")
	ErrInsufficientSpace    = errors.New("insufficient disk space")
	ErrInvalidConfig        = errors.New("invalid configuration")
)

Common errors

View Source
var DefaultReconnectConfig = ReconnectConfig{
	MaxRetries:     5,
	InitialBackoff: time.Second,
	MaxBackoff:     30 * time.Second,
	Multiplier:     2.0,
}

DefaultReconnectConfig 默认重连配置

Functions

This section is empty.

Types

type AddTorrentOptions

type AddTorrentOptions struct {
	// AddAtPaused 是否以暂停状态添加种子
	// true: 种子添加后处于暂停状态,需要手动启动
	// false: 种子添加后自动开始下载(默认行为)
	// 注意:此参数替代了原有的 autoStart 配置,逻辑相反
	// autoStart=true 等价于 AddAtPaused=false
	AddAtPaused bool

	// SavePath 保存路径(可选)
	// 空字符串表示使用下载器默认路径
	SavePath string

	// Category 种子分类(可选)
	Category string

	// Tags 种子标签(可选,逗号分隔)
	Tags string

	// UploadSpeedLimitMB 上传速度限制 (MB/s)
	// 0 表示不限制
	// Deprecated: 使用 UploadSpeedLimitKBs(KB/s,更细粒度)。若同时设置两者,UploadSpeedLimitKBs 优先。
	UploadSpeedLimitMB int

	// UploadSpeedLimitKBs 上传速度限制 (KB/s)
	// 0 表示不限制。KB 单位比 MB 更细粒度,适合按站点精确配置。
	UploadSpeedLimitKBs int

	// DownloadSpeedLimitKBs 下载速度限制 (KB/s)
	// 0 表示不限制
	DownloadSpeedLimitKBs int

	// AdvanceOptions 高级选项(可选)
	// 用于传递客户端特定的高级配置
	AdvanceOptions map[string]any
}

AddTorrentOptions 添加种子的选项 用于统一控制种子添加行为,替代原有的分散参数

func ToAddTorrentOptions

func ToAddTorrentOptions(config DownloaderConfig, category, tags, savePath string) AddTorrentOptions

ToAddTorrentOptions 将配置转换为 AddTorrentOptions 用于向后兼容,将 autoStart 映射到 AddAtPaused

func (AddTorrentOptions) EffectiveDownloadLimitBytes added in v0.26.0

func (o AddTorrentOptions) EffectiveDownloadLimitBytes() int64

EffectiveDownloadLimitBytes returns the effective download speed limit in bytes/second. Returns 0 for unlimited.

func (AddTorrentOptions) EffectiveUploadLimitBytes added in v0.26.0

func (o AddTorrentOptions) EffectiveUploadLimitBytes() int64

EffectiveUploadLimitBytes returns the effective upload speed limit in bytes/second. Priority: UploadSpeedLimitKBs (new) > UploadSpeedLimitMB (deprecated). Returns 0 for unlimited.

type AddTorrentResult

type AddTorrentResult struct {
	Success bool   // 是否成功
	Message any    // 消息(错误信息或成功信息)
	ID      string // 种子ID(成功时返回)
	Hash    string // 种子哈希
}

AddTorrentResult 添加种子的结果

type ClientStatus

type ClientStatus struct {
	UpSpeed       int64 // 上传速度 (bytes/s)
	DlSpeed       int64 // 下载速度 (bytes/s)
	UpData        int64 // 历史总上传量 (bytes)
	DlData        int64 // 历史总下载量 (bytes)
	SessionUpData int64 // 本次启动上传量 (bytes)
	SessionDlData int64 // 本次启动下载量 (bytes)
}

type DiskInfo added in v0.14.0

type DiskInfo struct {
	Path      string // 路径
	FreeSpace int64  // 可用空间 (bytes)
	TotalSize int64  // 总空间 (bytes), 0 表示未知
}

DiskInfo 磁盘信息

type DownloadTaskInfo

type DownloadTaskInfo struct {
	Name          string
	Hash          string
	SizeLeft      int64
	DownloadSpeed int64
	ETA           time.Duration
}

DownloadTaskInfo 下载任务信息

type Downloader

type Downloader interface {
	// Authenticate 认证连接到下载器
	// 返回错误如果认证失败
	Authenticate() error

	// Ping 检查下载器连接是否正常
	Ping() (bool, error)

	// GetClientVersion 获取下载器版本
	GetClientVersion() (string, error)

	// GetClientStatus 获取下载器状态(上传/下载速度等)
	GetClientStatus() (ClientStatus, error)

	// GetClientFreeSpace 获取下载器所在磁盘的可用空间
	// 返回可用空间(字节)
	GetClientFreeSpace(ctx context.Context) (int64, error)

	// GetIncompletePendingBytes 聚合所有"未下载完成的活跃种子"还需要下载的字节数。
	// 用于计算 effective_free_space = client_free - pending - reserved,
	// 修复 Issue #299:qBit 默认 preallocate_all=false,新推送的种子直到下载
	// 完成才反映在 OS 空闲空间,多个 worker 并发推送会基于过时数据通过检查。
	//
	// 计入聚合的状态(qBit):downloading / stalledDL / queuedDL / forcedDL /
	// metaDL / allocating / pausedDL / checkingDL。Transmission:status==3,4。
	// 实现层应跳过 nil/error 单条种子,错误不应中断聚合。
	GetIncompletePendingBytes(ctx context.Context) (int64, error)

	// GetAllTorrents 获取所有种子列表
	GetAllTorrents() ([]Torrent, error)

	// GetTorrentsBy 根据过滤条件获取种子列表
	GetTorrentsBy(filter TorrentFilter) ([]Torrent, error)

	// GetTorrent 获取单个种子信息
	GetTorrent(id string) (Torrent, error)

	// AddTorrentEx 添加种子到下载器(新接口)
	// url: 种子URL或磁力链接
	// opt: 添加选项
	AddTorrentEx(url string, opt AddTorrentOptions) (AddTorrentResult, error)

	// AddTorrentFileEx 添加种子文件到下载器(新接口)
	// fileData: 种子文件的二进制数据
	// opt: 添加选项
	AddTorrentFileEx(fileData []byte, opt AddTorrentOptions) (AddTorrentResult, error)

	// PauseTorrent 暂停种子
	PauseTorrent(id string) error

	// ResumeTorrent 恢复种子
	ResumeTorrent(id string) error

	// RemoveTorrent 删除种子
	// removeData: 是否同时删除数据文件
	RemoveTorrent(id string, removeData bool) error

	// === 批量操作 ===
	PauseTorrents(ids []string) error
	ResumeTorrents(ids []string) error
	RemoveTorrents(ids []string, removeData bool) error

	// === 修改操作 ===
	SetTorrentCategory(id, category string) error
	SetTorrentTags(id, tags string) error
	SetTorrentSavePath(id, path string) error

	// === 维护操作 ===
	RecheckTorrent(id string) error

	// === 详情查询 ===
	GetTorrentFiles(id string) ([]TorrentFile, error)
	GetTorrentTrackers(id string) ([]TorrentTracker, error)

	// === 全局状态 ===
	GetDiskInfo() (DiskInfo, error)
	GetSpeedLimit() (SpeedLimit, error)
	SetSpeedLimit(limit SpeedLimit) error

	// GetClientPaths 获取下载器配置的保存路径列表
	GetClientPaths() ([]string, error)

	// GetClientLabels 获取下载器配置的标签列表
	GetClientLabels() ([]string, error)

	// GetType 获取下载器类型
	GetType() DownloaderType

	// GetName 获取下载器实例名称
	GetName() string

	// IsHealthy 检查下载器是否健康可用
	IsHealthy() bool

	// Close 关闭下载器连接,释放资源
	Close() error

	// AddTorrent 添加种子到下载器(旧接口,向后兼容)
	// Deprecated: 请使用 AddTorrentFileEx 替代
	AddTorrent(fileData []byte, category, tags string) error

	// AddTorrentWithPath 添加种子到下载器并指定下载路径(旧接口,向后兼容)
	// Deprecated: 请使用 AddTorrentFileEx 替代
	AddTorrentWithPath(fileData []byte, category, tags, downloadPath string) error

	// CheckTorrentExists 检查种子是否已存在于下载器中
	// torrentHash: 种子的 info hash
	// 返回 true 如果种子存在
	CheckTorrentExists(torrentHash string) (bool, error)

	// GetDiskSpace 获取下载器所在磁盘的可用空间
	// Deprecated: 请使用 GetClientFreeSpace 替代
	GetDiskSpace(ctx context.Context) (int64, error)

	// CanAddTorrent 检查是否有足够空间添加指定大小的种子
	// fileSize: 种子文件大小(字节)
	CanAddTorrent(ctx context.Context, fileSize int64) (bool, error)

	// ProcessSingleTorrentFile 处理单个种子文件
	// filePath: 种子文件路径
	// category: 分类
	// tags: 标签
	ProcessSingleTorrentFile(ctx context.Context, filePath, category, tags string) error
}

Downloader 下载器核心接口 所有下载器实现(qBittorrent、Transmission 等)都必须实现此接口

type DownloaderConfig

type DownloaderConfig interface {
	// GetType 获取下载器类型
	GetType() DownloaderType
	// GetURL 获取下载器 URL
	GetURL() string
	// GetUsername 获取用户名
	GetUsername() string
	// GetPassword 获取密码
	GetPassword() string
	// GetAutoStart 获取是否自动开始下载
	// Deprecated: 请使用 AddTorrentOptions.AddAtPaused 替代
	// autoStart=true 等价于 AddAtPaused=false
	GetAutoStart() bool
	// Validate 验证配置是否有效
	Validate() error
}

DownloaderConfig 下载器配置接口

type DownloaderDBRecord added in v0.6.0

type DownloaderDBRecord struct {
	Name      string
	Type      DownloaderType
	URL       string
	Username  string
	Password  string
	IsDefault bool
	Enabled   bool
	AutoStart bool
}

DownloaderDBRecord 表示数据库中的下载器配置记录

type DownloaderFactory

type DownloaderFactory func(config DownloaderConfig, name string) (Downloader, error)

DownloaderFactory 下载器工厂函数类型 用于根据配置创建下载器实例

type DownloaderManager

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

DownloaderManager 下载器管理器 负责管理多个下载器实例,支持工厂注册和实例获取

func NewDownloaderManager

func NewDownloaderManager() *DownloaderManager

NewDownloaderManager 创建下载器管理器

func NewDownloaderManagerWithConfig

func NewDownloaderManagerWithConfig(reconnectConfig ReconnectConfig) *DownloaderManager

NewDownloaderManagerWithConfig 创建带自定义重连配置的下载器管理器

func (*DownloaderManager) CalculateBackoff

func (dm *DownloaderManager) CalculateBackoff(attempt int) time.Duration

CalculateBackoff 计算指数退避时间

func (*DownloaderManager) CloseAll

func (dm *DownloaderManager) CloseAll()

CloseAll 关闭所有下载器实例

func (*DownloaderManager) CreateFromConfig added in v0.6.0

func (dm *DownloaderManager) CreateFromConfig(config DownloaderConfig, name string) (Downloader, error)

CreateFromConfig 从配置创建临时下载器实例(不注册到管理器) 调用方需要负责调用 Close() 释放资源

func (*DownloaderManager) GetAllDownloaderStatus

func (dm *DownloaderManager) GetAllDownloaderStatus() []DownloaderStatus

GetAllDownloaderStatus 获取所有下载器状态

func (*DownloaderManager) GetDefaultDownloader

func (dm *DownloaderManager) GetDefaultDownloader() (Downloader, error)

GetDefaultDownloader 获取默认下载器

func (*DownloaderManager) GetDownloader

func (dm *DownloaderManager) GetDownloader(name string) (Downloader, error)

GetDownloader 获取或创建下载器实例

func (*DownloaderManager) GetDownloaderForSite

func (dm *DownloaderManager) GetDownloaderForSite(siteName string) (Downloader, error)

GetDownloaderForSite 获取站点对应的下载器 如果站点有指定下载器则使用,否则使用默认下载器

func (*DownloaderManager) GetDownloaderHealth

func (dm *DownloaderManager) GetDownloaderHealth(name string) (bool, error)

GetDownloaderHealth 获取下载器健康状态

func (*DownloaderManager) GetErrorCount

func (dm *DownloaderManager) GetErrorCount(name string) int

GetErrorCount 获取下载器错误计数

func (*DownloaderManager) HasFactory added in v0.6.0

func (dm *DownloaderManager) HasFactory(dlType DownloaderType) bool

HasFactory 检查是否已注册指定类型的工厂

func (*DownloaderManager) ListDownloaders

func (dm *DownloaderManager) ListDownloaders() []string

ListDownloaders 列出所有已注册的下载器配置

func (*DownloaderManager) ReconnectDownloader

func (dm *DownloaderManager) ReconnectDownloader(name string) error

ReconnectDownloader 重新连接指定下载器

func (*DownloaderManager) RegisterConfig

func (dm *DownloaderManager) RegisterConfig(name string, config DownloaderConfig, isDefault bool) error

RegisterConfig 注册下载器配置

func (*DownloaderManager) RegisterFactory

func (dm *DownloaderManager) RegisterFactory(dlType DownloaderType, factory DownloaderFactory)

RegisterFactory 注册下载器工厂

func (*DownloaderManager) RemoveDownloader

func (dm *DownloaderManager) RemoveDownloader(name string) error

RemoveDownloader 移除下载器配置和实例

func (*DownloaderManager) SetSiteDownloader

func (dm *DownloaderManager) SetSiteDownloader(siteName, downloaderName string)

SetSiteDownloader 设置站点使用的下载器

func (*DownloaderManager) SyncFromDB added in v0.6.0

func (dm *DownloaderManager) SyncFromDB(records []DownloaderDBRecord)

SyncFromDB 从数据库记录同步下载器配置 处理新增、删除、更新三种情况,确保内存状态与数据库一致

type DownloaderStatus

type DownloaderStatus struct {
	Name        string    `json:"name"`
	Type        string    `json:"type"`
	IsHealthy   bool      `json:"is_healthy"`
	IsDefault   bool      `json:"is_default"`
	LastChecked time.Time `json:"last_checked"`
	ErrorCount  int       `json:"error_count"`
}

DownloaderStatus 下载器状态

type DownloaderType

type DownloaderType string

DownloaderType 定义下载器类型

const (
	DownloaderQBittorrent  DownloaderType = "qbittorrent"
	DownloaderTransmission DownloaderType = "transmission"
)

type GenericConfig added in v0.6.0

type GenericConfig struct {
	Type      DownloaderType `json:"type"`
	URL       string         `json:"url"`
	Username  string         `json:"username"`
	Password  string         `json:"password"`
	AutoStart bool           `json:"auto_start"`
}

GenericConfig 通用下载器配置 用于不需要特定实现的场景,如健康检查、临时实例创建等

func NewGenericConfig added in v0.6.0

func NewGenericConfig(dlType DownloaderType, url, username, password string, autoStart bool) *GenericConfig

NewGenericConfig 创建通用下载器配置

func (*GenericConfig) GetAutoStart added in v0.6.0

func (c *GenericConfig) GetAutoStart() bool

GetAutoStart 获取是否自动开始下载

func (*GenericConfig) GetPassword added in v0.6.0

func (c *GenericConfig) GetPassword() string

GetPassword 获取密码

func (*GenericConfig) GetType added in v0.6.0

func (c *GenericConfig) GetType() DownloaderType

GetType 获取下载器类型

func (*GenericConfig) GetURL added in v0.6.0

func (c *GenericConfig) GetURL() string

GetURL 获取下载器 URL

func (*GenericConfig) GetUsername added in v0.6.0

func (c *GenericConfig) GetUsername() string

GetUsername 获取用户名

func (*GenericConfig) Validate added in v0.6.0

func (c *GenericConfig) Validate() error

Validate 验证配置是否有效

type HTTPDoer added in v0.13.0

type HTTPDoer interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPDoer defines the minimal contract used by downloader clients.

type ReconnectConfig

type ReconnectConfig struct {
	MaxRetries     int           // 最大重试次数
	InitialBackoff time.Duration // 初始退避时间
	MaxBackoff     time.Duration // 最大退避时间
	Multiplier     float64       // 退避时间乘数
}

ReconnectConfig 重连配置

type RequestsHTTPDoer added in v0.13.0

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

RequestsHTTPDoer adapts github.com/sunerpy/requests Session to HTTPDoer.

func NewRequestsHTTPDoer added in v0.13.0

func NewRequestsHTTPDoer(baseURL string, timeout time.Duration) *RequestsHTTPDoer

func (*RequestsHTTPDoer) Close added in v0.13.0

func (d *RequestsHTTPDoer) Close() error

func (*RequestsHTTPDoer) Do added in v0.13.0

func (d *RequestsHTTPDoer) Do(req *http.Request) (*http.Response, error)

type SpeedLimit added in v0.14.0

type SpeedLimit struct {
	DownloadLimit int64 // 下载限速 (bytes/s), 0=不限
	UploadLimit   int64 // 上传限速 (bytes/s), 0=不限
	LimitEnabled  bool  // 是否启用限速
}

SpeedLimit 速度限制

type Torrent

type Torrent struct {
	ID              string       // 种子ID
	InfoHash        string       // 种子哈希
	Name            string       // 种子名称
	Progress        float64      // 下载进度 (0.0-1.0)
	IsCompleted     bool         // 是否已完成
	Ratio           float64      // 分享率
	DateAdded       int64        // 添加时间 (Unix timestamp)
	SavePath        string       // 保存路径
	Label           string       // 标签
	Category        string       // 分类 (qBit: category, TR: labels[0])
	Tags            string       // 标签 (qBit: tags, TR: labels joined)
	State           TorrentState // 状态
	TotalSize       int64        // 总大小 (bytes)
	UploadSpeed     int64        // 上传速度 (bytes/s)
	DownloadSpeed   int64        // 下载速度 (bytes/s)
	ETA             int64        // 预计剩余时间(秒), -1=无限, 0=完成
	SeedingTime     int64        // 做种时间(秒)
	Tracker         string       // 主 Tracker URL
	CompletionOn    int64        // 完成时间 (Unix timestamp), 0=未完成
	NumSeeds        int          // 种子数
	NumPeers        int          // 下载者数
	Availability    float64      // 可用性 (0.0-1.0+)
	ContentPath     string       // 内容路径 (文件/文件夹的完整路径)
	TotalUploaded   int64        // 总上传量 (bytes)
	TotalDownloaded int64        // 总下载量 (bytes)
	AmountLeft      int64        // 剩余下载字节数 (qBit:amount_left, TR:left_until_done);用于"待下载累计"磁盘预算
	Raw             any          // 原始数据
	ClientID        string       // 客户端ID
}

Torrent 种子信息

type TorrentFile added in v0.14.0

type TorrentFile struct {
	Index    int     // 文件索引
	Name     string  // 文件路径/名称
	Size     int64   // 文件大小 (bytes)
	Progress float64 // 下载进度 (0.0-1.0)
	Priority int     // 优先级 (0=不下载, 1=普通, 6=高, 7=最高)
}

TorrentFile 种子内的文件信息

type TorrentFilter

type TorrentFilter struct {
	IDs      []string      // 按ID过滤
	Hashes   []string      // 按哈希过滤
	Complete *bool         // 按完成状态过滤
	State    *TorrentState // 按状态过滤
}

TorrentFilter 种子过滤条件

type TorrentState

type TorrentState string

TorrentState 种子状态

const (
	TorrentDownloading TorrentState = "downloading"
	TorrentSeeding     TorrentState = "seeding"
	TorrentPaused      TorrentState = "paused"
	TorrentStopped     TorrentState = "stopped"
	TorrentQueued      TorrentState = "queued"
	TorrentChecking    TorrentState = "checking"
	TorrentError       TorrentState = "error"
	TorrentUnknown     TorrentState = "unknown"
)

type TorrentTracker added in v0.14.0

type TorrentTracker struct {
	URL     string // Tracker URL
	Status  int    // 状态 (0=禁用, 1=未联系, 2=工作中, 3=更新中, 4=出错)
	Peers   int    // Peer 数
	Seeds   int    // Seed 数
	Leeches int    // Leech 数
	Message string // 状态消息
}

TorrentTracker Tracker 信息

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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