engine

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2026 License: MIT Imports: 45 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package engine owns the anacrolix/torrent client and everything torrent-shaped: adding, removing, starting and stopping torrents, limits, seed goals, categories and tags, and the state the rest of piecemeal reads.

Nothing outside this package imports anacrolix. Reads (List, Get, Transfer) are served from a snapshot that a background loop refreshes every second, so they never wait on the client's lock or on disk I/O.

Index

Constants

View Source
const (
	// IncompleteDefault follows the global setting.
	IncompleteDefault = "default"
	// IncompleteOff keeps the category's torrents in their save path.
	IncompleteOff = "off"
	// IncompleteOn uses the category's own incomplete folder.
	IncompleteOn = "on"
)

A category's incomplete folder modes.

View Source
const (
	// LayoutOriginal keeps the torrent's own structure: multi-file torrents
	// in their root folder, single files directly in the save path.
	LayoutOriginal = "Original"
	// LayoutSubfolder also puts a single file in a folder named after it.
	LayoutSubfolder = "Subfolder"
	// LayoutNoSubfolder drops a multi-file torrent's root folder.
	LayoutNoSubfolder = "NoSubfolder"
)

Content layouts, as qBittorrent names them.

View Source
const (
	ActionDefault        = "default"
	ActionStop           = "stop"
	ActionRemove         = "remove"
	ActionRemoveWithData = "removeWithData"
)

What happens when a torrent reaches its seeding goals. A torrent or a category with ActionDefault follows the next level: the torrent's category, then the global seedGoalAction setting.

View Source
const (
	ModeDefault = "default"
	ModeAny     = "any"
	ModeAll     = "all"
)

How a torrent's goals combine: it reaches them when any one is met, or only when every goal that is set is. ModeDefault follows the category, then the global seedGoalMode setting.

Variables

View Source
var (
	ErrNotFound      = errors.New("not found")
	ErrExists        = errors.New("already exists")
	ErrInvalid       = errors.New("invalid")
	ErrPathForbidden = errors.New("path is outside the allowed roots")
	ErrClosed        = errors.New("engine closed")
)

Errors returned by engine methods. Callers map them to API responses.

View Source
var ErrBusy = errors.New("too many metadata fetches running")

ErrBusy is returned when too many metadata fetches are running.

Functions

func AvailableFraction added in v1.1.0

func AvailableFraction(counts []int, start, end int) float64

AvailableFraction is the share of pieces in [start, end) that at least one connected peer has.

func CheckRoots added in v0.6.0

func CheckRoots(roots []string, dirs ...string) error

CheckRoots refuses allowed roots that overlap a directory piecemeal keeps its own files in, such as the data directory: users and RSS rules could otherwise overwrite those files with a torrent's, or read them with the torrent creator. Empty dirs are ignored.

func DistributedCopies added in v1.1.0

func DistributedCopies(counts []int) float64

DistributedCopies is how many complete copies connected peers hold together: the rarest piece's count, plus the fraction of pieces more peers have, as libtorrent reports it.

func IncompleteFromQBittorrent added in v1.1.0

func IncompleteFromQBittorrent(use *bool, path, global string) *string

IncompleteFromQBittorrent turns qBittorrent's useDownloadPath and downloadPath into AddParams.IncompletePath: none when useDownloadPath is false, the path when there is one (even without useDownloadPath), the global folder when useDownloadPath is true without a path, and the default when neither is given.

func ParseIPFilter added in v0.4.0

func ParseIPFilter(r io.Reader) (ranges []iplist.Range, bad int, err error)

ParseIPFilter reads an IP filter in any of the common formats, line by line:

  • eMule .dat: "first - last , access , description"; ranges with an access level of 128 or more are allowed and skipped
  • PeerGuardian .p2p: "description:first-last"
  • one IP address or CIDR range per line

Blank lines and lines starting with # or // are ignored. Lines that parse as none of these are counted in bad.

func ParseSource

func ParseSource(b []byte) (magnet string, mi []byte, err error)

ParseSource turns the body of an add request, a magnet URI or a .torrent file, into AddParams' Magnet or Metainfo.

Types

type AddParams

type AddParams struct {
	Magnet   string
	Metainfo []byte
	// SavePath overrides the category's and the default save path.
	SavePath string
	// IncompletePath is where the data stays until the torrent completes:
	// "" for nowhere, nil to follow the category, then the global setting.
	// A relative path is inside the global incomplete folder.
	IncompletePath *string
	// AutoManaged turns automatic management on or off; nil follows the
	// autoManagement setting, or is off when SavePath is set. An
	// automatically managed torrent takes its category's paths, whatever
	// SavePath and IncompletePath say.
	AutoManaged *bool
	Category    string
	Tags        []string
	// Stopped adds the torrent without starting it; nil follows the
	// addStopped setting.
	Stopped        *bool
	Sequential     bool
	FirstLastPiece bool
	// Name replaces the torrent's display name.
	Name string
	// Seed goals; nil leaves the defaults.
	RatioLimit               *float64
	SeedingTimeLimit         *int64
	InactiveSeedingTimeLimit *int64
	// SeedGoalAction and SeedGoalMode; empty is the default.
	SeedGoalAction string
	SeedGoalMode   string
	// SkipChecking trusts existing data instead of hashing it.
	SkipChecking bool
	// ContentLayout is Original (the default), Subfolder or NoSubfolder.
	ContentLayout string
}

AddParams describes a torrent to add. Exactly one of Magnet and Metainfo is set.

type Bus

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

Bus fans engine events out to subscribers.

func (*Bus) Subscribe

func (b *Bus) Subscribe(buffer int) *Subscription

Subscribe returns a subscription with room for buffer events.

type Category

type Category struct {
	Name     string `json:"name"`
	SavePath string `` /* 177-byte string literal not displayed */
	// IncompletePathMode and IncompletePath are the category's incomplete
	// folder.
	IncompletePathMode string `` /* 190-byte string literal not displayed */
	IncompletePath     string `json:"incompletePath" doc:"With incompletePathMode on: where the category's incomplete torrents are kept."`
	// Seeding goals for the category's torrents that follow the default.
	RatioLimit               float64 `json:"ratioLimit" doc:"-2 follows the global setting, -1 is unlimited."`
	SeedingTimeLimit         int64   `json:"seedingTimeLimit" doc:"Minutes. -2 follows the global setting, -1 is unlimited."`
	InactiveSeedingTimeLimit int64   `json:"inactiveSeedingTimeLimit" doc:"Minutes. -2 follows the global setting, -1 is unlimited."`
	SeedGoalAction           string  `` /* 160-byte string literal not displayed */
	SeedGoalMode             string  `` /* 129-byte string literal not displayed */
}

Category groups torrents and can give them a save path, an incomplete folder and seeding goals.

func NewCategory added in v1.1.0

func NewCategory(name string) Category

NewCategory returns a category with no save path whose seeding goals follow the global settings.

type Config

type Config struct {
	// DataDir holds anacrolix's piece completion database.
	DataDir string
	// AllowedRoots confines every save path. The default save path and
	// category paths must be inside one of them too.
	AllowedRoots []string
	// Mmap selects anacrolix's memory-mapped file I/O instead of pread and
	// pwrite. See docs/plan.md for why it is off by default.
	Mmap bool
	// DisableIPv6 stops listening and dialling on IPv6, for networks such as
	// an IPv4-only VPN tunnel.
	DisableIPv6 bool
	// ListenHost is the address to bind the peer listeners to; empty is all.
	ListenHost string
	// PortForwarded is true when something outside the engine (NAT-PMP)
	// forwards the peer port, which turns off anacrolix's UPnP and makes
	// the peerPort setting irrelevant.
	PortForwarded bool
	// InitialPort is the forwarded port to start on when PortForwarded.
	InitialPort int
	// Bind, when set, keeps every connection the client makes on one
	// network interface, such as a VPN's.
	Bind *netbind.Binder
	// TickInterval is how often the snapshot is refreshed. Default 1s.
	TickInterval time.Duration
	// CheckpointInterval is how often counters are written to the store.
	// Default 1m.
	CheckpointInterval time.Duration

	// ClientConfig, when set, adjusts the anacrolix configuration before the
	// client is created. Tests use it to stay off the network.
	ClientConfig func(*torrent.ClientConfig)
	// contains filtered or unexported fields
}

Config is what the engine needs from piecemeal's configuration.

type CreateParams added in v0.4.0

type CreateParams struct {
	// SourcePath is the file or folder, inside an allowed root.
	SourcePath string `json:"sourcePath"`
	// PieceSize in bytes; 0 picks one from the total size.
	PieceSize int64      `json:"pieceSize,omitempty" minimum:"0"`
	Private   bool       `json:"private,omitempty"`
	Trackers  [][]string `json:"trackers,omitempty" doc:"Tiers of announce URLs."`
	WebSeeds  []string   `json:"webSeeds,omitempty"`
	Comment   string     `json:"comment,omitempty"`
	Source    string     `json:"source,omitempty" doc:"The info dictionary's source field, which some private trackers require."`
	// StartSeeding adds the new torrent, seeding from SourcePath.
	StartSeeding bool `json:"startSeeding,omitempty"`
}

CreateParams describes a torrent to create from files on disk.

type CreateTask added in v0.4.0

type CreateTask struct {
	ID         string       `json:"id"`
	Params     CreateParams `json:"params"`
	Status     string       `json:"status" enum:"queued,running,finished,failed"`
	Progress   float64      `json:"progress" doc:"0 to 1."`
	Error      string       `json:"error,omitempty"`
	Hash       string       `json:"hash,omitempty" doc:"The new torrent's infohash, once finished."`
	AddedAt    time.Time    `json:"addedAt"`
	StartedAt  *time.Time   `json:"startedAt,omitempty"`
	FinishedAt *time.Time   `json:"finishedAt,omitempty"`
}

CreateTask is a torrent being created, or done.

type Engine

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

Engine is the torrent engine.

func New

func New(ctx context.Context, cfg Config, st *store.Store, sm *settings.Manager, log *slog.Logger) (*Engine, error)

New loads every torrent from the store and starts the client. Close it when done.

func (*Engine) Add

func (e *Engine) Add(ctx context.Context, p AddParams) (string, error)

Add adds a torrent and returns its infohash. Adding a torrent that is already present returns ErrExists with its hash.

func (*Engine) AddPeers

func (e *Engine) AddPeers(ctx context.Context, addrs []string, hashes ...string) error

AddPeers gives running torrents peer addresses (host:port) to connect to.

func (*Engine) AddTags

func (e *Engine) AddTags(ctx context.Context, tags []string, hashes ...string) error

AddTags tags torrents, creating tags that don't exist.

func (*Engine) AddTrackers added in v0.4.0

func (e *Engine) AddTrackers(ctx context.Context, hash string, urls []string) error

AddTrackers adds announce URLs, each in a tier of its own after the existing ones. URLs the torrent already has are skipped.

func (*Engine) BoundInterface added in v1.3.0

func (e *Engine) BoundInterface() (name string, up bool)

BoundInterface returns the interface connections are bound to, "" for none, and whether it is up.

func (*Engine) Categories

func (e *Engine) Categories() []Category

Categories returns every category, by name.

func (*Engine) Close

func (e *Engine) Close() error

Close stops the client after writing every torrent's counters.

func (*Engine) CompleteFile added in v0.4.0

func (e *Engine) CompleteFile(hash string, index int) (string, error)

CompleteFile returns where a torrent's file is on disk, once all of it is downloaded and verified.

func (*Engine) Confine added in v0.4.0

func (e *Engine) Confine(path string) (string, error)

Confine returns path, cleaned, if it is inside an allowed root once symlinks are resolved, and ErrPathForbidden otherwise.

func (*Engine) CreateTags

func (e *Engine) CreateTags(ctx context.Context, tags ...string) error

CreateTags creates tags.

func (*Engine) CreateTasks added in v0.4.0

func (e *Engine) CreateTasks() []CreateTask

CreateTasks returns every creation task, oldest first.

func (*Engine) CreateTorrent added in v0.4.0

func (e *Engine) CreateTorrent(p CreateParams) (string, error)

CreateTorrent queues a torrent to be created and returns its task ID.

func (*Engine) CreatedTorrent added in v0.4.0

func (e *Engine) CreatedTorrent(id string) ([]byte, error)

CreatedTorrent returns a finished task's .torrent file.

func (*Engine) DeleteCategories

func (e *Engine) DeleteCategories(ctx context.Context, names ...string) error

DeleteCategories deletes categories; their torrents are left without one.

func (*Engine) DeleteCreateTask added in v0.4.0

func (e *Engine) DeleteCreateTask(id string) error

DeleteCreateTask cancels a task if it's running and forgets it.

func (*Engine) DeleteTags

func (e *Engine) DeleteTags(ctx context.Context, tags ...string) error

DeleteTags deletes tags and removes them from every torrent.

func (*Engine) EditTracker added in v0.4.0

func (e *Engine) EditTracker(ctx context.Context, hash, from, to string) error

EditTracker replaces one announce URL with another.

func (*Engine) Events

func (e *Engine) Events() *Bus

Events returns the engine's event bus.

func (*Engine) FetchMetadata added in v1.1.0

func (e *Engine) FetchMetadata(magnet string) (string, []byte, error)

FetchMetadata starts fetching a magnet's metadata, or reports on a fetch already started. It returns the info hash, and the torrent file once the metadata is known; nil means it's still being fetched. A torrent already in piecemeal answers with its own torrent file.

func (*Engine) FetchedMetadata added in v1.1.0

func (e *Engine) FetchedMetadata(hash string) []byte

FetchedMetadata returns a fetched torrent file by info hash, without starting a fetch.

func (*Engine) Files

func (e *Engine) Files(hash string) ([]File, error)

Files returns a torrent's files. A torrent without metadata has none.

func (*Engine) FreeSpace added in v0.4.0

func (e *Engine) FreeSpace(path string) (int64, error)

FreeSpace returns the free bytes on the filesystem holding path, which must be inside an allowed root, or of its closest existing parent: -1 when unknown.

func (*Engine) Get

func (e *Engine) Get(hash string) (Torrent, bool)

Get returns one torrent's status.

func (*Engine) List

func (e *Engine) List() []Torrent

List returns every torrent's status, oldest first.

func (*Engine) ListenAddrs

func (e *Engine) ListenAddrs() []net.Addr

ListenAddrs returns the addresses the client accepts peers on.

func (*Engine) Move added in v0.4.0

func (e *Engine) Move(ctx context.Context, hash, savePath string) error

Move moves a torrent's data to another save path and turns automatic management off, as qBittorrent's setLocation does. It returns once the move has started; the torrent is in the moving state until it's done, and resumes if it was running. A torrent still in its incomplete folder keeps its data there and moves to the new save path once complete.

func (*Engine) PathAllowed added in v0.4.0

func (e *Engine) PathAllowed(path string) bool

PathAllowed reports whether path is inside an allowed root.

func (*Engine) PeerLog added in v1.1.0

func (e *Engine) PeerLog(after int64) []PeerLogEntry

PeerLog returns the refused and banned addresses logged after the entry with ID after, oldest first; -1 returns them all.

func (*Engine) Peers

func (e *Engine) Peers(hash string) ([]Peer, error)

Peers returns a running torrent's connected peers.

func (*Engine) PieceAvailability added in v1.1.0

func (e *Engine) PieceAvailability(hash string) ([]int, error)

PieceAvailability returns, for each piece, how many connected peers have it. It is nil when the torrent has no metadata or isn't running.

func (*Engine) PieceHashes added in v0.4.0

func (e *Engine) PieceHashes(hash string) ([]string, error)

PieceHashes returns a torrent's v1 piece hashes, hex.

func (*Engine) Pieces

func (e *Engine) Pieces(hash string) (string, error)

Pieces returns a torrent's piece states as a string with one byte per piece: 0 missing, 1 downloading, 2 complete, 3 checking.

func (*Engine) Port

func (e *Engine) Port() int

Port returns the port the client listens for peers on.

func (*Engine) PutCategory

func (e *Engine) PutCategory(ctx context.Context, c Category, create bool) error

PutCategory creates a category or changes its paths and seeding goals. Manually managed torrents in it stay where they are; automatically managed ones follow a change of its paths, or switch to manual management, as relocateOnCategoryPathChange says. Start from NewCategory: zero limits are goals of 0. An empty action, mode or incomplete folder mode is the default.

func (*Engine) QueueMove added in v0.4.0

func (e *Engine) QueueMove(ctx context.Context, how string, hashes ...string) error

QueueMove moves torrents in the download queue: "top", "bottom", "up" or "down".

func (*Engine) Reannounce

func (e *Engine) Reannounce(ctx context.Context, hashes ...string) error

Reannounce asks the trackers and the DHT for peers now, in the background. anacrolix keeps announcing on its own schedule; it has no way to bring that forward, so these are extra announces whose peers are handed to the torrent.

func (*Engine) Recheck

func (e *Engine) Recheck(ctx context.Context, hashes ...string) error

Recheck verifies torrents' data against their piece hashes. They wait in the check queue for their turn; until their data is verified again they neither download nor seed. Stopped torrents are checked too and stay stopped.

func (*Engine) Relocate added in v1.1.0

func (e *Engine) Relocate(ctx context.Context, savePath string, incompletePath *string, hashes ...string) error

Relocate changes torrents' save path, incomplete folder, or both, with a single move of their data, and turns automatic management off. An empty savePath keeps the save path; a nil incompletePath keeps the incomplete folder, and "" removes it. The data stays in whichever of the two folders holds it, except that a new incomplete folder takes the data of a torrent that never completed, as SetIncompletePath says.

func (*Engine) Remove

func (e *Engine) Remove(ctx context.Context, deleteData bool, hashes ...string) error

Remove removes torrents, and their downloaded data with deleteData.

func (*Engine) RemoveTags

func (e *Engine) RemoveTags(ctx context.Context, tags []string, hashes ...string) error

RemoveTags removes tags from torrents. No tags means all of them.

func (*Engine) RemoveTrackers added in v0.4.0

func (e *Engine) RemoveTrackers(ctx context.Context, hash string, urls []string) error

RemoveTrackers removes announce URLs.

func (*Engine) Rename

func (e *Engine) Rename(ctx context.Context, hash, name string) error

Rename changes a torrent's display name.

func (*Engine) RenamePath added in v0.4.0

func (e *Engine) RenamePath(hash, oldPath, newPath string) error

RenamePath renames a file, or a folder and everything in it. Paths are relative to the save path with / separators, as torrents/files reports them. The files on disk move with it.

func (*Engine) SavePathOf

func (e *Engine) SavePathOf(hash string) (string, error)

SavePathOf returns where a torrent's content is.

func (*Engine) SetAutoManaged added in v1.1.0

func (e *Engine) SetAutoManaged(ctx context.Context, on bool, hashes ...string) error

SetAutoManaged turns automatic management on or off. Turning it on moves the torrents to their category's paths; turning it off leaves them where they are.

func (*Engine) SetCategory

func (e *Engine) SetCategory(ctx context.Context, category string, hashes ...string) error

SetCategory moves torrents into a category, or out of any with "". Automatically managed torrents follow the category's paths, or switch to manual management, as relocateOnCategoryChange says.

func (*Engine) SetComment added in v1.1.0

func (e *Engine) SetComment(ctx context.Context, comment string, hashes ...string) error

SetComment replaces the comment the torrents show; the torrent file is unchanged.

func (*Engine) SetFilePriority

func (e *Engine) SetFilePriority(ctx context.Context, hash string, indices []int, p Priority) error

SetFilePriority sets the priority of the files at indices.

func (*Engine) SetFirstLastPiece

func (e *Engine) SetFirstLastPiece(ctx context.Context, on bool, hashes ...string) error

SetFirstLastPiece turns first and last piece priority on or off.

func (*Engine) SetForced

func (e *Engine) SetForced(ctx context.Context, forced bool, hashes ...string) error

SetForced sets force start: forced torrents ignore queueing limits.

func (*Engine) SetIncompletePath added in v1.1.0

func (e *Engine) SetIncompletePath(ctx context.Context, path string, hashes ...string) error

SetIncompletePath changes torrents' incomplete folder; "" means none. Data still in the old folder moves to the new one, or to the save path without one, and a torrent that never completed moves into the new one. Automatic management turns off, as with Move.

func (*Engine) SetPort

func (e *Engine) SetPort(port int) error

SetPort moves the peer listeners to port, recreating the client. Torrents keep running; their peers reconnect on the new port.

func (*Engine) SetSequential

func (e *Engine) SetSequential(ctx context.Context, on bool, hashes ...string) error

SetSequential turns sequential download on or off.

func (*Engine) SetShareLimits

func (e *Engine) SetShareLimits(ctx context.Context, l ShareLimits, hashes ...string) error

SetShareLimits sets per-torrent seed goals.

func (*Engine) SetTrackers added in v0.4.0

func (e *Engine) SetTrackers(ctx context.Context, hash string, tiers [][]string) error

SetTrackers replaces a torrent's announce list. Each inner list is a tier; empty tiers are dropped.

func (*Engine) SetWebSeeds added in v0.4.0

func (e *Engine) SetWebSeeds(ctx context.Context, hash string, urls []string) error

SetWebSeeds replaces a torrent's web seed URLs.

func (*Engine) Start

func (e *Engine) Start(ctx context.Context, hashes ...string) error

Start resumes stopped torrents.

func (*Engine) Stop

func (e *Engine) Stop(ctx context.Context, hashes ...string) error

Stop stops torrents: they leave the swarm, and keep their data and record. Stopping cancels a recheck; data of unknown completion is still checked when the torrent starts again.

func (*Engine) Tags

func (e *Engine) Tags() []string

Tags returns every tag, sorted.

func (*Engine) TorrentFile added in v0.4.0

func (e *Engine) TorrentFile(hash string) ([]byte, error)

TorrentFile returns a torrent's .torrent file, once its metadata is known, with its current trackers and web seeds.

func (*Engine) TrackerMap added in v0.4.0

func (e *Engine) TrackerMap() map[string][]string

TrackerMap returns every announce URL in use with the torrents using it.

func (*Engine) Trackers

func (e *Engine) Trackers(hash string) ([]Tracker, error)

Trackers returns a torrent's trackers, by tier.

func (*Engine) Transfer

func (e *Engine) Transfer() TransferStatus

Transfer returns the client-wide transfer state.

func (*Engine) WebSeeds added in v0.4.0

func (e *Engine) WebSeeds(hash string) ([]string, error)

WebSeeds returns a torrent's web seed URLs.

type Event

type Event struct {
	Type     EventType
	Torrent  *Torrent
	Hash     string
	Transfer *TransferStatus
}

Event is a change in the engine.

type EventType

type EventType string

EventType says what an Event is about.

const (
	// EventTorrent carries a torrent's new status, after it was added or
	// anything about it changed.
	EventTorrent EventType = "torrent"
	// EventTorrentRemoved carries the hash of a removed torrent.
	EventTorrentRemoved EventType = "torrentRemoved"
	// EventTransfer carries the new transfer status.
	EventTransfer EventType = "transfer"
	// EventCategories means the categories changed.
	EventCategories EventType = "categories"
	// EventTags means the tags changed.
	EventTags EventType = "tags"
	// EventSettings means the settings changed.
	EventSettings EventType = "settings"
)

Event types.

type File

type File struct {
	Index    int      `json:"index"`
	Path     string   `json:"path" doc:"Path relative to the save path, with / separators, after the content layout and any renames."`
	Size     int64    `json:"size"`
	Progress float64  `json:"progress" doc:"0 to 1. Stopped torrents report 0 for files they haven't finished."`
	Priority Priority `json:"priority" enum:"0,1,6,7" doc:"0 skip, 1 normal, 6 high, 7 highest."`
	// The range of pieces the file spans, end exclusive.
	PieceStart int `json:"pieceStart"`
	PieceEnd   int `json:"pieceEnd"`
}

File is one file of a torrent.

type ImportOptions added in v0.6.0

type ImportOptions struct {
	// AllowedRoots confine save paths, as in the engine's configuration.
	AllowedRoots []string
	// Trust marks the pieces of complete torrents as verified instead of
	// letting piecemeal check them at its next start.
	Trust bool
	// DryRun checks everything but writes nothing.
	DryRun bool
}

ImportOptions control Import.

type ImportResult added in v0.6.0

type ImportResult struct {
	Source, Hash, Name string
	// Skipped says why it wasn't imported, for one already in piecemeal.
	Skipped string
	Err     error
}

ImportResult is what happened to one imported torrent.

func Import added in v0.6.0

func Import(ctx context.Context, st *store.Store, dataDir string, items []Imported, o ImportOptions) []ImportResult

Import writes torrents from another client into piecemeal's database, for the engine to load at its next start. Their data is checked then, unless Trust is set. piecemeal must not be running; the caller holds the data directory lock.

type Imported added in v0.6.0

type Imported struct {
	// Source is the file it was read from, for messages.
	Source   string
	Metainfo []byte
	SavePath string
	// IncompletePath is the torrent's incomplete folder, "" for none, and
	// InIncompletePath is set when its data is there rather than in
	// SavePath.
	IncompletePath   string
	InIncompletePath bool
	// AutoManaged is automatic torrent management.
	AutoManaged bool
	// Name replaces the torrent's own name; "" keeps it.
	Name     string
	Category string
	Tags     []string
	Stopped  bool
	// Times and totals from the other client.
	AddedAt, CompletedAt          time.Time
	Uploaded, Downloaded          int64
	SeedingSeconds, ActiveSeconds int64
	RatioLimit                    float64 // -2 follows the global setting, -1 is unlimited
	SeedingTimeLimit              int64   // minutes, same values
	InactiveSeedingTimeLimit      int64   // minutes, same values
	Sequential, FirstLastPiece    bool
	// Paths are each file's path relative to SavePath, with / separators,
	// after the other client's renames; "" or missing keeps the torrent's.
	Paths []string
	// Skip marks files that aren't downloaded.
	Skip []bool
	// Trackers and WebSeeds replace the torrent file's when not nil.
	Trackers [][]string
	WebSeeds []string
	// Complete is set when the other client had all wanted data.
	Complete bool
}

Imported is a torrent read from another client's state, for Import.

func ReadQBittorrent added in v0.6.0

func ReadQBittorrent(dir string) ([]Imported, []error)

ReadQBittorrent reads the torrents of qBittorrent's BT_backup directory: *.fastresume with their *.torrent. dir may also be qBittorrent's data directory that holds BT_backup.

func ReadTransmission added in v0.6.0

func ReadTransmission(dir string) ([]Imported, []error)

ReadTransmission reads the torrents of a Transmission configuration directory: torrents/*.torrent with their resume/*.resume. Labels become tags, and the first label also the category: Radarr and Sonarr label their downloads in Transmission with what is their category in qBittorrent.

type InterfaceStatus added in v1.3.0

type InterfaceStatus struct {
	Name string `json:"name" doc:"The interface's name, such as wg0."`
	Up   bool   `json:"up" doc:"False while the interface is down or gone: nothing goes out until it's back."`
}

InterfaceStatus is the network interface connections are bound to.

type Peer

type Peer struct {
	Address    string  `json:"address"`
	Client     string  `json:"client"`
	Network    string  `json:"network" doc:"tcp, utp, webrtc or webseed."`
	Source     string  `json:"source" doc:"How the peer was found."`
	Encryption string  `json:"encryption" enum:"none,header,rc4" doc:"header: obfuscated handshake only; rc4: the whole connection."`
	Progress   float64 `json:"progress" doc:"How much of the torrent the peer has, 0 to 1."`
	DownRate   int64   `json:"downloadRate" doc:"Bytes per second from the peer."`
	UpRate     int64   `json:"uploadRate" doc:"Bytes per second to the peer."`
	Downloaded int64   `json:"downloaded" doc:"Payload bytes from the peer this session."`
	Uploaded   int64   `json:"uploaded" doc:"Payload bytes to the peer this session."`
}

Peer is a connected peer.

type PeerLogEntry added in v1.1.0

type PeerLogEntry struct {
	ID      int64
	IP      string
	Time    time.Time
	Blocked bool // refused by the IP filter; false for a banned address
	Reason  string
}

PeerLogEntry is an address the IP filter refused, or a banned one: what qBittorrent's log/peers reports.

type Priority

type Priority int

Priority is a file download priority, with qBittorrent's values.

const (
	PrioritySkip    Priority = 0
	PriorityNormal  Priority = 1
	PriorityHigh    Priority = 6
	PriorityHighest Priority = 7
)

File priorities.

type SeedGoals added in v1.1.0

type SeedGoals struct {
	RatioLimit               float64 `json:"ratioLimit"`
	SeedingTimeLimit         int64   `json:"seedingTimeLimit" doc:"Minutes."`
	InactiveSeedingTimeLimit int64   `json:"inactiveSeedingTimeLimit" doc:"Minutes."`
	Action                   string  `json:"action" enum:"stop,remove,removeWithData"`
	Mode                     string  `json:"mode" enum:"any,all"`
}

SeedGoals are the seeding goals that apply to a torrent: its own, or where it follows the default, its category's, or else the global settings. Limits are -1 when unlimited.

type ShareLimits

type ShareLimits struct {
	RatioLimit               float64
	SeedingTimeLimit         int64
	InactiveSeedingTimeLimit int64
	// Action and Mode are left as they are when empty.
	Action string
	Mode   string
}

ShareLimits are per-torrent seed goals. -2 and the default action and mode follow the category, then the global settings; -1 is unlimited. Times are in minutes.

type State

type State string

State is a torrent's state. Stopped, queued and checking torrents are told apart by Torrent.Complete into their downloading and seeding variants.

const (
	StateMetadata           State = "metadata"
	StateChecking           State = "checking"
	StateDownloading        State = "downloading"
	StateStalledDownloading State = "stalledDownloading"
	StateSeeding            State = "seeding"
	StateStalledSeeding     State = "stalledSeeding"
	StateStopped            State = "stopped"
	StateQueued             State = "queued"
	StateQueuedForChecking  State = "queuedForChecking"
	StateMoving             State = "moving"
	StateError              State = "error"
)

Torrent states.

type Subscription

type Subscription struct {
	C <-chan Event
	// contains filtered or unexported fields
}

Subscription receives events until it is closed. A subscriber that falls more than its buffer behind is dropped: C is closed, and it should re-read the full state and subscribe again.

func (*Subscription) Close

func (s *Subscription) Close()

Close ends the subscription.

type Torrent

type Torrent struct {
	Hash        string   `json:"hash" doc:"SHA-1 infohash, hex."`
	Name        string   `json:"name"`
	State       State    `` /* 137-byte string literal not displayed */
	Complete    bool     `json:"complete" doc:"Every wanted file is downloaded."`
	HasMetadata bool     `json:"hasMetadata"`
	Progress    float64  `json:"progress" doc:"Fraction of the wanted bytes downloaded, 0 to 1."`
	Size        int64    `json:"size" doc:"Bytes in the wanted files."`
	TotalSize   int64    `json:"totalSize" doc:"Bytes in all files."`
	Completed   int64    `json:"completed" doc:"Wanted bytes downloaded and verified."`
	Downloaded  int64    `json:"downloaded" doc:"Payload bytes downloaded, all time."`
	Uploaded    int64    `json:"uploaded" doc:"Payload bytes uploaded, all time."`
	SessionDown int64    `json:"sessionDownloaded" doc:"Payload bytes downloaded since piecemeal started."`
	SessionUp   int64    `json:"sessionUploaded" doc:"Payload bytes uploaded since piecemeal started."`
	MultiFile   bool     `json:"multiFile" doc:"The torrent's files are in a root folder, even if there is only one."`
	Trackers    int      `json:"trackers" doc:"Number of trackers."`
	DownRate    int64    `json:"downloadRate" doc:"Bytes per second."`
	UpRate      int64    `json:"uploadRate" doc:"Bytes per second."`
	ETA         int64    `json:"eta" doc:"Seconds until complete, -1 when unknown."`
	Ratio       float64  `json:"ratio"`
	Seeds       int      `json:"seeds" doc:"Connected seeds."`
	Peers       int      `json:"peers" doc:"Connected peers that are not seeds."`
	SwarmPeers  int      `json:"swarmPeers" doc:"Peers known in the swarm."`
	SavePath    string   `json:"savePath" doc:"Where the torrent's data goes; while it's incomplete, it may be in incompletePath instead."`
	ContentPath string   `json:"contentPath" doc:"The torrent's file, or its top folder, or the save path when its files share no folder."`
	RootPath    string   `json:"rootPath" doc:"The torrent's top folder, empty when it has none."`
	Layout      string   `json:"contentLayout" enum:"Original,Subfolder,NoSubfolder"`
	Category    string   `json:"category"`
	Tags        []string `json:"tags"`
	AddedAt     int64    `json:"addedAt" doc:"Unix time."`
	CompletedAt int64    `json:"completedAt" doc:"Unix time, 0 if never completed."`
	LastActive  int64    `json:"lastActivityAt" doc:"Unix time of the last payload transfer, 0 if none."`
	SeedingTime int64    `json:"seedingTime" doc:"Seconds spent seeding, all time."`
	ActiveTime  int64    `json:"activeTime" doc:"Seconds spent running, all time."`
	Stopped     bool     `json:"stopped"`
	Forced      bool     `json:"forced"`
	Sequential  bool     `json:"sequential"`
	FirstLast   bool     `json:"firstLastPiece"`
	Private     bool     `json:"private"`
	PieceSize   int64    `json:"pieceSize"`
	Pieces      int      `json:"pieces"`
	PiecesHave  int      `json:"piecesHave"`
	Magnet      string   `json:"magnet"`
	Comment     string   `json:"comment"`
	CreatedBy   string   `json:"createdBy"`
	CreatedAt   int64    `json:"createdAt" doc:"Unix time the torrent was created, 0 if unknown."`
	Tracker     string   `json:"tracker" doc:"The first tracker's URL."`
	Error       string   `json:"error,omitempty"`

	RatioLimit               float64   `json:"ratioLimit" doc:"-2 follows the category, then the global setting; -1 is unlimited."`
	SeedingTimeLimit         int64     `json:"seedingTimeLimit" doc:"Minutes. -2 follows the category, then the global setting; -1 is unlimited."`
	InactiveSeedingTimeLimit int64     `json:"inactiveSeedingTimeLimit" doc:"Minutes. -2 follows the category, then the global setting; -1 is unlimited."`
	SeedGoalAction           string    `` /* 181-byte string literal not displayed */
	SeedGoalMode             string    `` /* 148-byte string literal not displayed */
	SeedGoals                SeedGoals `json:"seedGoals" doc:"The seeding goals in effect, after following the defaults."`
	QueuePosition            int64     `json:"queuePosition"`
	IncompletePath           string    `json:"incompletePath" doc:"Where the data stays until the torrent completes, then it moves to savePath; empty for none."`
	AutoManaged              bool      `json:"autoManaged" doc:"Automatic management: the save path and incomplete folder follow the category."`
}

Torrent is a torrent as the API reports it.

type Tracker

type Tracker struct {
	URL  string `json:"url"`
	Tier int    `json:"tier"`
}

Tracker is one of a torrent's trackers.

type TransferStatus

type TransferStatus struct {
	DownRate          int64  `json:"downloadRate" doc:"Bytes per second."`
	UpRate            int64  `json:"uploadRate" doc:"Bytes per second."`
	SessionDownloaded int64  `json:"sessionDownloaded" doc:"Payload bytes downloaded since piecemeal started."`
	SessionUploaded   int64  `json:"sessionUploaded" doc:"Payload bytes uploaded since piecemeal started."`
	DownloadLimit     int64  `json:"downloadLimit" doc:"The limit in effect, bytes per second, 0 for unlimited."`
	UploadLimit       int64  `json:"uploadLimit" doc:"The limit in effect, bytes per second, 0 for unlimited."`
	AltSpeedEnabled   bool   `json:"altSpeedEnabled"`
	Port              int    `json:"port" doc:"The port peers connect to."`
	DHTNodes          int    `json:"dhtNodes"`
	Peers             int    `json:"peers" doc:"Connected peers across all torrents."`
	FreeSpace         int64  `json:"freeSpace" doc:"Free bytes on the default save path's filesystem, -1 if unknown."`
	Torrents          int    `json:"torrents"`
	Connection        string `json:"connection" enum:"connected,firewalled,disconnected"`
	// Interface is a value, not a pointer, so tick's comparison of two
	// statuses sees whether it changed.
	Interface InterfaceStatus `json:"interface,omitzero" doc:"The network interface connections are bound to (PIECEMEAL_BIND_INTERFACE), when set."`
}

TransferStatus is the client-wide transfer state.

Directories

Path Synopsis
Package enginetest has helpers for tests that need a BitTorrent swarm: a seeder serving generated content on loopback, and client settings that keep anacrolix off the network.
Package enginetest has helpers for tests that need a BitTorrent swarm: a seeder serving generated content on loopback, and client settings that keep anacrolix off the network.

Jump to

Keyboard shortcuts

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