core

package
v1.0.45 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: MIT Imports: 39 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
	// PrioLow files are downloaded after all the normal and high ones are complete. The engine has no
	// priority below normal, so they are simply not requested until then (see applyFiles and refreshLow).
	PrioLow int8 = -2
)

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).

View Source
const PendingGrace = 10 * time.Second

PendingGrace is how long the window made for adding torrents has the queue to itself. The main window polls the queue too, and would take the items for its own dialog; it only gets what has waited this long, which is a sign that no window for adding came up (no WebView2, say).

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 = &CodedError{Code: "torrent.busy", Msg: "раздача сейчас перемещается, подождите"}

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

View Source
var ErrIconPending = fmt.Errorf("%w: fetching in the background", ErrNotFound)

ErrIconPending is ErrNotFound with the added meaning that a fetch of the icon was just started (or was already running) in the background: unlike a confirmed absence, a caller must not remember this answer for long, since the icon (or the confirmed absence) may be ready within moments.

Functions

func AllowLocalFetches added in v1.0.25

func AllowLocalFetches(on bool)

AllowLocalFetches is for tests: the links may lead to this computer.

func FetchTorrent added in v1.0.25

func FetchTorrent(ctx context.Context, link string) ([]byte, error)

FetchTorrent downloads the file a link leads to. It does not look inside: that is for metainfo.Load.

func IconType added in v1.0.26

func IconType(data []byte) string

IconType is the type of image data if it is one that may be an icon, "" otherwise.

func ParsePriority

func ParsePriority(s string) (int8, error)

ParsePriority converts the API names to a priority.

func TrackerName added in v1.0.26

func TrackerName(announce string) string

TrackerName is the name of the tracker whose announce address is given: "" when there is no host in it.

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 WithRawFile added in v1.0.24

func WithRawFile(raw []byte) AddOption

WithRawFile hands over the .torrent file as it was given. It is what the copies are written from, so keys the metainfo type does not know (a tracker's publisher-url) are not lost, and it is where the comment and the publisher page of the torrent are read from.

func WithSavePath

func WithSavePath(dir string) AddOption

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

func WithSkipCheck added in v1.0.32

func WithSkipCheck() AddOption

WithSkipCheck trusts the files already on disk as complete instead of hashing them.

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 CodedError added in v1.0.25

type CodedError struct {
	Code string
	Args []string
	Msg  string
	Err  error // what caused it, if anything
}

CodedError is a plain Coder.

func (*CodedError) ErrCode added in v1.0.25

func (e *CodedError) ErrCode() (string, []string)

func (*CodedError) Error added in v1.0.25

func (e *CodedError) Error() string

func (*CodedError) Unwrap added in v1.0.25

func (e *CodedError) Unwrap() error

type Coder added in v1.0.25

type Coder interface {
	ErrCode() (code string, args []string)
}

Coder is an error that names itself with a code and gives the pieces of its text that change (a file name, an address). A client that speaks another language than the message builds the text from them: the code says which text, the arguments fill in the blanks. The message stays what the person reads in Russian, and the log.

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"`
	Publisher       string    `json:"publisher"`    // the tracker that published it, as the file says
	PublisherURL    string    `json:"publisherUrl"` // the page of the torrent on that tracker (http or https), "" if none
	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"`
	// options of the torrent
	Sequential  bool   `json:"sequential"`
	EdgePieces  bool   `json:"edgePieces"`
	MoveDone    string `json:"moveDone"`    // this torrent's own "move when finished" folder, "" = the global setting
	MoveDoneOff bool   `json:"moveDoneOff"` // never move this torrent when it finishes, even if a global/own folder is set
	Label       string `json:"label"`
}

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
	// DetailCode and DetailArgs say it for a client that words it itself: "limit.ratio" [ratio], "limit.time" [number, unit d/h/min].
	DetailCode string
	DetailArgs []string
}

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
	Check    float64 `json:"check,omitempty"` // while the torrent is checked: the share of the file already checked (0 is sent as missing)
	Checking bool    `json:"checking,omitempty"`
	Waiting  bool    `json:"checkWaiting,omitempty"` // a recheck that includes this file waits for its turn
}

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.

Locks, and the order they may be taken in:

portCtl -> portMu             starting and stopping the router mapping; portCtl is held across the slow
                              Stop, portMu only for the pointer, so PortStatus never waits for the router
m.mu -> cfg.mu                cfg.Get() is read under m.mu in a few places
state.mu -> cfg.mu            likewise inside state.with/touch/view callbacks
lowMu, evMu, peerMu, manualMu, self.mu, iconMu  leaves: nothing else is taken while one of them is held

m.mu and state.mu are never nested: no state.with/touch/view callback takes m.mu, and nothing calls into the state store while holding m.mu. The state store writes the file under its own lock, so a callback must stay short. Do not call the engine's torrent methods that block, or emit(), under any of these; emit only hands the event to another goroutine. checkLine takes m.mu and snapshotRecords takes state.mu, so neither may be called with m.mu held. A new lock, or a new nesting, belongs in this list.

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) AddPeers added in v1.0.21

func (m *Manager) AddPeers(hash string, raw []string) (PeerAddResult, error)

AddPeers hands peers the user knows about to a torrent: "ip:port", "[ipv6]:port" or "name:port" (the name is looked up now and again whenever the peer is tried again). The addresses are kept with the torrent (see manualpeers.go), so a restart does not lose them. Peers of a private torrent are fine too: the user asked for these ones, they are not found by DHT or PEX.

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. GlobalRatio returns lifetime downloaded/uploaded bytes and the share ratio across every torrent ever added. Like the per-torrent ratio (see ratio above), each torrent counts in the denominator with what was downloaded here or what is on disk, whichever is more, so data acquired outside this client does not inflate the ratio or drag it down to zero.

func (*Manager) List

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

List returns the status of every torrent, newest first.

func (*Manager) ManualPeers added in v1.0.21

func (m *Manager) ManualPeers(hash string) ([]ManualPeerInfo, error)

ManualPeers lists the peers saved for a torrent, with whether each is connected and whether it has gone stale.

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, if a slot is free under MaxConcurrentMoves, starts in the background at once (watch Status.Moving); otherwise it waits in line, and the torrent is left untouched until its turn comes, same as a torrent that has not been asked to move at all. 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) QueueExternalAdd added in v1.0.1

func (m *Manager) QueueExternalAdd(p PendingAdd)

QueueExternalAdd remembers one item for TakePendingAdds.

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. With a limit on simultaneous checks already in use, it waits its turn instead — at the front of that line, ahead of anything else waiting (see acquireRecheck) — and Status.CheckQueued shows its place. It runs in the background; Status.Checking is true only once it actually starts.

func (*Manager) RecheckFiles added in v1.0.43

func (m *Manager) RecheckFiles(hash string, files []int) error

RecheckFiles checks only the given files of a torrent (the pieces they lie in); none means the whole torrent.

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) RemoveManualPeers added in v1.0.21

func (m *Manager) RemoveManualPeers(hash string, addrs []string) (int, error)

RemoveManualPeers forgets saved peers (by the addresses ManualPeers gave) and drops their connections.

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) SetAllPaused added in v1.0.35

func (m *Manager) SetAllPaused(paused bool) int

SetAllPaused pauses or resumes every torrent at once (the "pause all" button and the tray menu). Resuming resumes every paused torrent, also those the person paused one by one earlier, as the other clients do. It returns how many torrents changed.

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) SetEdgePieces added in v1.0.1

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

SetEdgePieces switches "first and last pieces first" for one torrent.

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) SetMaxActiveSeeds added in v1.0.18

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

SetMaxActiveSeeds limits how many finished torrents share at the same time (0 = no limit). The rest wait for a place; see applySeedQueue for who gets one.

func (*Manager) SetMoveDone added in v1.0.1

func (m *Manager) SetMoveDone(hash string, enabled bool, path string) error

SetMoveDone sets whether and where this torrent moves when it finishes. enabled=false means never move it, even if a global or own folder is set. enabled=true with an empty path falls back to the global folder; a non-empty path overrides it (and is created if it is missing).

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, raw []byte) (StagedTorrent, error)

Stage parses a torrent and keeps it for AddBatch.

func (*Manager) StagedInfo added in v1.0.1

func (m *Manager) StagedInfo(id string) (StagedTorrent, bool)

StagedInfo describes a staged torrent again, for a client that only has its id (see PendingAdd).

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) StatusExtra added in v1.0.1

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

StatusExtra returns the extras of one torrent.

func (*Manager) TakePendingAdds added in v1.0.1

func (m *Manager) TakePendingAdds(forAddWindow bool) []PendingAdd

TakePendingAdds returns and clears the items queued by QueueExternalAdd. The window for adding takes all of them (forAddWindow); any other caller, the main window, only those that have waited PendingGrace.

func (*Manager) TrackerIcon added in v1.0.26

func (m *Manager) TrackerIcon(ctx context.Context, site string) (data []byte, contentType string, err error)

TrackerIcon returns the icon of a site (its domain, "rutracker.org"): from the folder of the icons, or fetched in the background. A confirmed absence (or icons switched off) is ErrNotFound; a fetch still in flight is the more specific ErrIconPending, so a caller can tell the two apart (see its doc).

func (*Manager) TrafficStats added in v1.0.38

func (m *Manager) TrafficStats(now time.Time) TrafficStats

TrafficStats sums the buckets up for the session, the last day, week and month.

func (*Manager) Unstage

func (m *Manager) Unstage(id string)

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

type ManualPeerInfo added in v1.0.21

type ManualPeerInfo struct {
	Addr      string    `json:"addr"`
	Added     time.Time `json:"added"`
	LastSeen  time.Time `json:"lastSeen"`
	Connected bool      `json:"connected"` // a connection with it exists now
	Stale     bool      `json:"stale"`     // not connected for manualPeerStale: worth removing
}

ManualPeerInfo is a saved peer as the interface shows it.

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, manual, other
	Network    string  `json:"network"`
}

Peer is one connection of a torrent.

type PeerAddResult added in v1.0.21

type PeerAddResult struct {
	Added  int             `json:"added"`  // new to the torrent: the engine will try to connect to them
	Known  int             `json:"known"`  // fine, but the torrent has them already (or the engine dropped them)
	Errors []PeerAddrError `json:"errors"` // the ones that could not be used
}

PeerAddResult is what AddPeers did with the addresses it was given.

type PeerAddrError added in v1.0.21

type PeerAddrError struct {
	Addr   string `json:"addr"`
	Reason string `json:"reason"`
}

PeerAddrError says why one of the given addresses was not used. Reason is one of "format" (not host:port), "port" (not 1..65535), "address" (unusable, such as 0.0.0.0 or a multicast address) and "resolve" (the name could not be looked up); the interface words it.

type PendingAdd added in v1.0.1

type PendingAdd struct {
	Kind   string `json:"kind"` // "stage" (see Stage/StagedInfo) or "magnet"
	Stage  string `json:"stage,omitempty"`
	Magnet string `json:"magnet,omitempty"`
}

PendingAdd is a magnet link or a staged .torrent (see Stage) waiting to be shown in the "Add torrents" dialog, put there by the desktop app or a second launch when the user opens a magnet link or a .torrent file from outside the app (Explorer, "Open with"), instead of it being added silently. The web page picks these up and opens the dialog with them on the list.

type PortReport

type PortReport struct {
	portmap.Status
	Verdict string `json:"verdict"`
	Advice  string `json:"advice"`
	// AdviceCode and AdviceArgs say the advice for a client that words it itself (see Coder).
	AdviceCode  string    `json:"adviceCode"`
	AdviceArgs  []string  `json:"adviceArgs,omitempty"`
	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
	// PublicIP and PublicIPv6 are our address as the outside sees it: what the peers report, or else what
	// the router says when that is a public one. Empty until something tells.
	PublicIP   string `json:"publicIP,omitempty"`
	PublicIPv6 string `json:"publicIPv6,omitempty"`
}

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"`
	Pad  bool   `json:"pad,omitempty"` // a padding file (BEP 47): kept for the indexes, not shown
}

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"`
	Active        bool      `json:"active"`     // moved data in the last few seconds
	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"`        // nonzero while a move is happening or queued: > 0 fraction copied, -1 a plain rename, -2 waiting in line for a free slot
	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)
	SeedQueued    int       `json:"seedQueued"`    // 0 = shares (or is not finished); N = place in the line for a place to share (1 = next)
	Sequential    bool      `json:"sequential"`
	HasMeta       bool      `json:"hasMetadata"`
	CopyPath      string    `json:"copyPath,omitempty"`
	Tracker       string    `json:"tracker"`               // the name of its main tracker (see mainTracker), "" if it has none; for the filter by tracker
	TrackerSite   string    `json:"trackerSite,omitempty"` // the site of that tracker, whose icon is the tracker's
}

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

type StatusExtra added in v1.0.1

type StatusExtra struct {
	ActiveSeconds     int64     `json:"activeSeconds"`     // time the torrent has been running (not paused), adds up across restarts
	LastTransfer      int64     `json:"lastTransfer"`      // seconds since data last moved in this session, -1 = not yet
	Availability      float64   `json:"availability"`      // distributed copies among the connected peers and us, right now
	LastSeedSeen      time.Time `json:"lastSeedSeen"`      // see record.LastSeedSeen
	LastFullAvailable time.Time `json:"lastFullAvailable"` // see record.LastFullAvailable
}

StatusExtra is what the Status tab shows besides the numbers of the torrent list.

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
	MoveDoneOff bool     `json:"moveDoneOff"` // never move this torrent when it finishes, even if a global folder is set
	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", "low", "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.

type Traffic added in v1.0.38

type Traffic struct {
	Down int64 `json:"down"`
	Up   int64 `json:"up"`
}

Traffic is the payload moved in one period.

type TrafficStats added in v1.0.38

type TrafficStats struct {
	Session Traffic   `json:"session"`
	Day     Traffic   `json:"day"`
	Week    Traffic   `json:"week"`
	Month   Traffic   `json:"month"`
	Since   time.Time `json:"since"`        // the first hour on record: a period that reaches further back is partly unknown
	Started time.Time `json:"sessionStart"` // when this session began
}

TrafficStats is the traffic of the periods the statistics window offers.

Jump to

Keyboard shortcuts

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