core

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2026 License: MIT Imports: 32 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 core is the torrent daemon engine: it wraps the BitTorrent client and adds .torrent copies, safe removal, disk preallocation, share ratio and media-friendly piece prioritisation.

Index

Constants

View Source
const (
	ErrKindDiskFull = "disk_full"
	ErrKindWrite    = "write"
	ErrKindOther    = "other"
)

Kinds of failure that stop a torrent.

View Source
const (
	PrioSkip   int8 = -1
	PrioNormal int8 = 0
	PrioHigh   int8 = 1
)

File priorities. The zero value is "normal" so records written before this feature existed keep downloading everything.

View Source
const (
	PortOpen     = "open"     // a peer from the internet connected to us
	PortMapped   = "mapped"   // router mapping is in place, no inbound peer seen yet
	PortCGNAT    = "cgnat"    // the router itself has a non-public address: forwarding is impossible
	PortClosed   = "closed"   // automatic forwarding is on but the router does not cooperate
	PortManual   = "manual"   // automatic forwarding is off
	PortChecking = "checking" // first check in progress
)

Verdicts of the port report.

View Source
const MaxLabelLen = 40

MaxLabelLen bounds label length (in runes).

Variables

View Source
var (
	ErrNotFound     = errors.New("torrent not found")
	ErrNoDiskSpace  = errors.New("not enough free disk space")
	ErrInvalidInput = errors.New("invalid torrent or magnet")
	ErrNoMetadata   = errors.New("torrent metadata is not available yet")
)
View Source
var ErrBusy = errors.New("torrent is being moved")

ErrBusy is returned for a torrent whose files are being moved.

Functions

func ParsePriority

func ParsePriority(s string) (int8, error)

ParsePriority converts the API names to a priority.

func ValidateNetwork

func ValidateNetwork(n config.Network) error

ValidateNetwork checks connection settings coming from the user.

func ValidateSchedule

func ValidateSchedule(sc config.AltSchedule) error

ValidateSchedule checks a schedule coming from the user.

Types

type AddDialogInfo

type AddDialogInfo struct {
	Defaults         config.AddDefaults `json:"defaults"`
	DataDir          string             `json:"dataDir"`
	Preallocate      bool               `json:"preallocate"`
	MoveCompletedDir string             `json:"moveCompletedDir"`
	MaxConns         int                `json:"maxConnsPerTorrent"`
	Labels           map[string]string  `json:"labels"` // label -> its folder
}

AddDialogInfo is what the dialog needs to start with: the saved defaults and the global settings they fall back to.

type AddOption

type AddOption func(*record)

AddOption tweaks how a torrent is added.

func WithFilePriorities

func WithFilePriorities(p []int8) AddOption

WithFilePriorities sets the per-file priorities of a torrent whose files are known.

func WithLabel

func WithLabel(label string) AddOption

WithLabel puts the torrent in a category. If the label has a folder configured, that is where the torrent is saved (unless WithSavePath says otherwise).

func WithOptions

func WithOptions(o TorrentOptions) AddOption

WithOptions applies all the options to the record of a torrent being added. The values are checked when the torrent is added (see resolveSaveDir); file priorities are converted by filePriorities.

func WithPaused

func WithPaused() AddOption

WithPaused adds the torrent stopped, so files can be chosen before anything downloads.

func WithSavePath

func WithSavePath(dir string) AddOption

WithSavePath saves the torrent in the given folder instead of the default one.

type BatchItem

type BatchItem struct {
	Stage    string         `json:"stage"`
	Magnet   string         `json:"magnet"`
	Infohash string         `json:"infohash"`
	Options  TorrentOptions `json:"options"`
}

BatchItem is one entry of the list in the "Add torrents" dialog: exactly one of Stage (a staged .torrent), Magnet or Infohash, plus its options.

type BatchResult

type BatchResult struct {
	Index  int    `json:"index"`
	OK     bool   `json:"ok"`
	Hash   string `json:"hash"`
	Name   string `json:"name"`
	Exists bool   `json:"exists"` // it was already in the client, nothing was changed
	Error  string `json:"error"`
}

BatchResult reports what happened to one entry.

type CreateJob

type CreateJob struct {
	ID      string    `json:"id"`
	Name    string    `json:"name"`
	Running bool      `json:"running"`
	Error   string    `json:"error"`
	Output  string    `json:"output"` // the written file
	Hash    string    `json:"hash"`
	Seeding bool      `json:"seeding"` // it was added to the client
	Started time.Time `json:"started"`
	Size    int64     `json:"size"` // bytes being hashed
}

CreateJob is the state of a torrent creation running in the background.

type CreateRequest

type CreateRequest struct {
	Source      string   `json:"source"`      // a file or a folder
	Output      string   `json:"output"`      // the .torrent to write, or a folder for it; empty = next to the source
	Trackers    []string `json:"trackers"`    // announce URLs, one tier each
	Comment     string   `json:"comment"`     //
	Private     bool     `json:"private"`     // no DHT/PEX for this torrent
	PieceLength int64    `json:"pieceLength"` // 0 = choose from the size
	Seed        bool     `json:"seed"`        // add it to the client and seed from Source
}

CreateRequest describes a .torrent file to be made from local data.

type Details

type Details struct {
	Hash            string    `json:"hash"`
	Name            string    `json:"name"`
	TotalSize       int64     `json:"totalSize"`
	Files           int       `json:"files"`
	Pieces          int       `json:"pieces"`
	PieceLength     int64     `json:"pieceLength"`
	PiecesDone      int       `json:"piecesDone"`
	Private         bool      `json:"private"`
	Comment         string    `json:"comment"`
	CreatedBy       string    `json:"createdBy"`
	CreatedAt       time.Time `json:"createdAt"` // zero if the torrent does not say
	Added           time.Time `json:"added"`
	SavePath        string    `json:"savePath"`
	CopyPath        string    `json:"copyPath"`
	Magnet          string    `json:"magnet"`
	Trackers        []Tracker `json:"trackers"`
	MaxConns        int       `json:"maxConns"`        // this torrent's own connection limit, 0 = the global setting
	ConnLimit       int       `json:"connLimit"`       // the limit actually in force
	RatioLimit      float64   `json:"ratioLimit"`      // this torrent's own stop-seeding ratio, 0 = the global setting
	RatioInForce    float64   `json:"ratioInForce"`    // the ratio limit actually in force, 0 = none
	SeedTimeLimit   int       `json:"seedTimeLimit"`   // this torrent's own seeding time limit in minutes, 0 = the global setting
	SeedTimeInForce int       `json:"seedTimeInForce"` // the seeding time limit actually in force, 0 = none
	SeedSeconds     int64     `json:"seedSeconds"`
}

Details is the static information about a torrent.

type Event

type Event struct {
	Kind   string // "completed" (a download finished) or "limit" (seeding stopped by a limit)
	Hash   string
	Name   string
	Detail string // for "limit": what was reached
}

Event is something the user may want to hear about even when no window is open. The desktop application turns these into Windows notifications.

type FileStatus

type FileStatus struct {
	Index    int     `json:"index"`
	Path     string  `json:"path"`
	Size     int64   `json:"size"`
	Done     int64   `json:"done"`
	Progress float64 `json:"progress"`
	Priority string  `json:"priority"` // skip | normal | high
}

FileStatus describes one file of a torrent.

type FoldersUpdate

type FoldersUpdate struct {
	DataDir        string
	TorrentCopyDir string // empty switches copies off
	// MoveCompletedDir is where finished downloads are moved; empty switches it off.
	MoveCompletedDir string
	// WatchDir is scanned for .torrent files to add; empty switches it off.
	WatchDir   string
	LabelPaths map[string]string
}

FoldersUpdate is a change of the global folders.

type Manager

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

Manager owns the engine client and everything layered on top of it.

func New

func New(cfg *config.Store, stateDir string) (*Manager, error)

New starts the engine. stateDir holds state.json and the piece-completion database.

func (*Manager) AddBatch

func (m *Manager) AddBatch(items []BatchItem) ([]BatchResult, error)

AddBatch adds every entry with its own options. A failing entry does not stop the others.

func (*Manager) AddDialog

func (m *Manager) AddDialog() AddDialogInfo

func (*Manager) AddFile

func (m *Manager) AddFile(path string, opts ...AddOption) (string, error)

AddFile adds a .torrent file: the file is copied into the configured copy folder.

func (*Manager) AddMagnet

func (m *Manager) AddMagnet(uri string, opts ...AddOption) (string, error)

AddMagnet adds a magnet link. Its .torrent copy is written once metadata arrives.

func (*Manager) AddMetaInfo

func (m *Manager) AddMetaInfo(mi *metainfo.MetaInfo, opts ...AddOption) (string, error)

AddMetaInfo adds torrent metadata and saves its .torrent copy.

func (*Manager) AddTracker

func (m *Manager) AddTracker(hash, raw string) error

AddTracker adds an announce URL to a torrent. It is remembered across restarts.

func (*Manager) Close

func (m *Manager) Close()

Close flushes counters and stops the engine.

func (*Manager) Create

func (m *Manager) Create(id string) (CreateJob, error)

Create returns the state of a creation job.

func (*Manager) DeleteFiles

func (m *Manager) DeleteFiles(hash string, indexes []int) (int, error)

DeleteFiles takes files out of a torrent for good: they are marked "do not download" and deleted from the disk. The engine is told afterwards that the pieces that held them are gone, so the torrent does not go on believing it has them. It returns how many files were deleted.

func (*Manager) Details

func (m *Manager) Details(hash string) (Details, error)

Details returns the general information about a torrent whose metadata is known.

func (*Manager) Files

func (m *Manager) Files(hash string) ([]FileStatus, error)

Files lists the files of a torrent whose metadata is known.

func (*Manager) GlobalRatio

func (m *Manager) GlobalRatio() (down, up int64, r float64)

GlobalRatio is the lifetime share ratio across all torrents, including removed ones.

func (*Manager) List

func (m *Manager) List() []Status

List returns the status of every torrent, newest first.

func (*Manager) MoveInQueue

func (m *Manager) MoveInQueue(hash, dir string) error

MoveInQueue changes the queue position of a torrent: "top", "up", "down" or "bottom".

func (*Manager) MoveStorage

func (m *Manager) MoveStorage(hash, dir string) error

MoveStorage moves the downloaded files of a torrent to another folder and keeps seeding from there. The check of the target is immediate; the move itself runs in the background (watch Status.Moving). On any failure the files stay where they were.

func (*Manager) OnEvent

func (m *Manager) OnEvent(fn func(Event))

OnEvent sets the function that receives events (nil removes it). It is called on its own goroutine, so it may take its time.

func (*Manager) OpenFile

func (m *Manager) OpenFile(hash string, index int) error

OpenFile shows one file of a torrent in the file manager (its folder opens with the file highlighted). A file that is not on the disk yet opens its folder, if that exists.

func (*Manager) OpenFolder

func (m *Manager) OpenFolder(hash string) error

OpenFolder shows a torrent's data in the file manager: the torrent's own folder or file when it exists, otherwise the folder it is saved in. The path comes from the torrent's record, never from the request.

func (*Manager) OpenStream

func (m *Manager) OpenStream(hash string, idx int) (*Stream, error)

OpenStream opens file idx for playback while it downloads. The reader prioritises the pieces around the read position, so seeking works before the download is done.

func (*Manager) Peers

func (m *Manager) Peers(hash string) ([]Peer, error)

Peers lists the current connections, the busiest first.

func (*Manager) Port

func (m *Manager) Port() int

Port returns the port the engine actually listens on.

func (*Manager) PortReport

func (m *Manager) PortReport() PortReport

PortReport returns the current reachability verdict with advice for the user.

func (*Manager) PortStatus

func (m *Manager) PortStatus() portmap.Status

PortStatus reports the router port-forwarding state.

func (*Manager) Recheck

func (m *Manager) Recheck(hash string) error

Recheck re-hashes all data of a torrent and corrects what the engine believes about it. It runs in the background; Status.Checking is true meanwhile.

func (*Manager) RefreshPort

func (m *Manager) RefreshPort()

RefreshPort forces an immediate port-mapping check.

func (*Manager) Remove

func (m *Manager) Remove(hash string, deleteData bool) error

Remove drops a torrent. With deleteData the downloaded files and the saved .torrent copy are deleted too (subject to the copy-removal policy).

func (*Manager) RestartInfo

func (m *Manager) RestartInfo() RestartInfo

RestartInfo compares the saved start-time settings with the ones the engine started with.

func (*Manager) SetAddDefaults

func (m *Manager) SetAddDefaults(d config.AddDefaults) error

SetAddDefaults saves the dialog's starting choices.

func (*Manager) SetAltSchedule

func (m *Manager) SetAltSchedule(sc config.AltSchedule) error

SetAltSchedule stores a new schedule and re-evaluates it right away.

func (*Manager) SetAltSpeed

func (m *Manager) SetAltSpeed(on bool) error

SetAltSpeed toggles the turtle mode.

func (*Manager) SetFilePriorities

func (m *Manager) SetFilePriorities(hash string, indexes []int, prio int8) error

SetFilePriorities sets the priority of the given files. Files that become wanted get their disk space reserved first; if the disk is too small nothing is changed.

func (*Manager) SetFolders

func (m *Manager) SetFolders(u FoldersUpdate) error

SetFolders changes where new torrents are saved and where .torrent copies go. Torrents that are already added keep their folders. Every folder is created and checked first, and nothing is changed if one of them is unusable.

func (*Manager) SetLabel

func (m *Manager) SetLabel(hash, label string) error

SetLabel puts the torrent in a category; an empty label clears it.

func (*Manager) SetLimits

func (m *Manager) SetLimits(down, up, altDown, altUp int) error

SetLimits changes the normal and alternative limits (KiB/s, 0 = unlimited).

func (*Manager) SetListenPort

func (m *Manager) SetListenPort(port int) error

SetListenPort stores the port for the next start. The engine keeps listening on its current port until the application is restarted.

func (*Manager) SetMaxActiveDownloads

func (m *Manager) SetMaxActiveDownloads(n int) error

SetMaxActiveDownloads limits how many incomplete torrents download at the same time (0 = no limit). The rest wait in the queue, in their queue order.

func (*Manager) SetNetwork

func (m *Manager) SetNetwork(n config.Network) error

SetNetwork stores new connection settings. The per-torrent connection limit takes effect immediately; everything else after the next start (see RestartInfo).

func (*Manager) SetPaused

func (m *Manager) SetPaused(hash string, paused bool) error

func (*Manager) SetPortMapping

func (m *Manager) SetPortMapping(on bool) error

SetPortMapping turns automatic router forwarding on or off without a restart.

func (*Manager) SetRatioLimit

func (m *Manager) SetRatioLimit(hash string, limit float64) error

SetRatioLimit sets the per-torrent stop-seeding ratio (0 = use the global default).

func (*Manager) SetSeedTimeLimit

func (m *Manager) SetSeedTimeLimit(hash string, minutes int) error

SetSeedTimeLimit sets the per-torrent limit in minutes (0 = use the global default).

func (*Manager) SetSequential

func (m *Manager) SetSequential(hash string, on bool) error

SetSequential enables in-order download with prioritised file edges, for playing media while it downloads.

func (*Manager) SetTorrentMaxConns

func (m *Manager) SetTorrentMaxConns(hash string, n int) error

SetTorrentMaxConns limits the connections of one torrent (0 = use the global setting).

func (*Manager) Stage

func (m *Manager) Stage(mi *metainfo.MetaInfo) (StagedTorrent, error)

Stage parses a torrent and keeps it for AddBatch.

func (*Manager) StartCreate

func (m *Manager) StartCreate(req CreateRequest) (CreateJob, error)

StartCreate validates the request and builds the torrent in the background. Hashing big data takes a while, so the caller follows the job with Create.

func (*Manager) Unstage

func (m *Manager) Unstage(id string)

Unstage forgets a staged torrent (it was removed from the list).

type Peer

type Peer struct {
	Addr       string  `json:"addr"`
	Client     string  `json:"client"`
	Progress   float64 `json:"progress"`
	DownRate   int64   `json:"downRate"`
	UpRate     int64   `json:"upRate"`
	Downloaded int64   `json:"downloaded"`
	Uploaded   int64   `json:"uploaded"`
	Incoming   bool    `json:"incoming"`
	Source     string  `json:"source"` // tracker, dht, pex, incoming, other
	Network    string  `json:"network"`
}

Peer is one connection of a torrent.

type PortReport

type PortReport struct {
	portmap.Status
	Verdict     string    `json:"verdict"`
	Advice      string    `json:"advice"`
	Inbound     int64     `json:"inbound"`     // inbound connections from the internet since start
	LastInbound time.Time `json:"lastInbound"` // zero if none yet
	WantedPort  int       `json:"wantedPort"`  // the configured port when the engine had to use another one, else 0
}

PortReport combines the router mapping with real inbound evidence.

type RestartInfo

type RestartInfo struct {
	Required bool     `json:"required"`
	Reasons  []string `json:"reasons"` // dht, pex, utp, tcp, ipv6, webseeds, incoming, encryption, halfopen, port
}

RestartInfo tells whether saved settings differ from what the running engine uses.

type StagedFile

type StagedFile struct {
	Path string `json:"path"`
	Size int64  `json:"size"`
}

StagedFile is one file of a staged torrent.

type StagedTorrent

type StagedTorrent struct {
	ID       string       `json:"id"`
	Name     string       `json:"name"`
	Hash     string       `json:"hash"`
	Size     int64        `json:"size"`
	Files    []StagedFile `json:"files"`
	Private  bool         `json:"private"`
	Comment  string       `json:"comment"`
	Trackers int          `json:"trackers"`
	Exists   bool         `json:"exists"` // it is already in the client
}

StagedTorrent describes a .torrent file that was put on the list.

type Status

type Status struct {
	Hash          string    `json:"hash"`
	Name          string    `json:"name"`
	Size          int64     `json:"size"`      // of the selected (not skipped) files
	TotalSize     int64     `json:"totalSize"` // of the whole torrent
	Done          int64     `json:"done"`
	Progress      float64   `json:"progress"`
	DownRate      int64     `json:"downRate"` // bytes/s
	Added         time.Time `json:"added"`    // when the torrent was added
	UpRate        int64     `json:"upRate"`
	Downloaded    int64     `json:"downloaded"` // lifetime payload bytes
	Uploaded      int64     `json:"uploaded"`
	Ratio         float64   `json:"ratio"`
	RatioLimit    float64   `json:"ratioLimit"`  // effective limit, 0 = none
	SeedSeconds   int64     `json:"seedSeconds"` // time spent seeding
	SeedLimit     int       `json:"seedLimit"`   // effective seeding time limit in minutes, 0 = none
	Peers         int       `json:"peers"`
	Seeds         int       `json:"seeds"`
	Paused        bool      `json:"paused"`
	Label         string    `json:"label"`
	SavePath      string    `json:"savePath"`
	Error         string    `json:"error"`         // why the engine stopped this torrent, "" if it did not
	ErrorKind     string    `json:"errorKind"`     // disk_full | write | other
	Checking      bool      `json:"checking"`      // files are being checked against their hashes
	CheckProgress float64   `json:"checkProgress"` // 0..1 while Checking
	CheckQueued   int       `json:"checkQueued"`   // 0 = not waiting; N = place in the line for a check of local files (1 = next)
	Moving        float64   `json:"moving"`        // > 0 while files are being moved (fraction copied; -1 = a plain rename)
	MoveError     string    `json:"moveError"`     // last failed move, "" if none
	MoveNote      string    `json:"moveNote"`      // a move that worked but left something behind
	Queued        int       `json:"queued"`        // 0 = not waiting; N = position in the wait line (1 = next)
	Sequential    bool      `json:"sequential"`
	HasMeta       bool      `json:"hasMetadata"`
	CopyPath      string    `json:"copyPath,omitempty"`
}

Status is a point-in-time view of one torrent.

type Stream

type Stream struct {
	torrent.Reader
	Name string
	Size int64
}

Stream is a seekable reader over one file that downloads what is being read first.

type TorrentOptions

type TorrentOptions struct {
	SavePath    string   `json:"savePath"`    // download folder, "" = the default one (or the label's)
	Label       string   `json:"label"`       //
	Paused      bool     `json:"paused"`      // add stopped
	Sequential  bool     `json:"sequential"`  // download in order (for playing while it downloads)
	EdgePieces  bool     `json:"edgePieces"`  // raise the first and last pieces of every file
	SkipCheck   bool     `json:"skipCheck"`   // take files already on disk as complete, without hashing them
	MoveDone    string   `json:"moveDone"`    // move here when finished, "" = the global setting
	Preallocate *bool    `json:"preallocate"` // reserve the disk space at once, nil = the global setting
	MaxConns    int      `json:"maxConns"`    // peer connections, 0 = the global setting
	Files       []string `json:"files"`       // per file: "skip", "normal" or "high" (torrent files only)
}

TorrentOptions are the settings a torrent can be given when it is added (the "Add torrents" dialog). Zero values mean "as in the settings".

type Tracker

type Tracker struct {
	URL   string `json:"url"`
	Tier  int    `json:"tier"`
	Added bool   `json:"added"` // added by the user rather than by the torrent itself
}

Tracker is one announce URL. The engine does not report tracker health, so there is no status here, only the list.

Jump to

Keyboard shortcuts

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