engine

package
v0.8.13 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 33 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 is a segmented HTTP downloader with pause/resume and dynamic segmentation.

  • Probe with "Range: bytes=0-0" to learn the size and Range support.
  • Split the file into N segments; one connection per segment, each writing directly at its offset in a preallocated .part file.
  • Dynamic segmentation: when a connection finishes its segment, it takes over the back half of the segment with the most bytes left, so fast connections keep working until the very end.
  • Progress (each segment's pos/end) is saved to <file>.part.json every 2s and on pause, so a download resumes after a pause or restart.

Servers without Range support fall back to one stream that can't resume.

Index

Constants

View Source
const MinSplit = 128 << 10

MinSplit is the smallest remaining range worth splitting for a new connection.

Variables

View Source
var (
	ErrEncrypted = errors.New("this stream is encrypted (DRM) and can't be downloaded")
	ErrLive      = errors.New("this is a live stream; only complete (on-demand) videos are supported")
)
View Source
var Categories = []string{"Video", "Music", "Images", "Documents", "E-books", "Compressed", "Disk images", "Programs", "Torrents", "Fonts"}
View Source
var ErrStalled = errors.New("connection stalled (no data received)")

ErrStalled means a connection received no data for too long; callers retry it like any other network error.

Functions

func CategoryOf

func CategoryOf(name string) string

CategoryOf returns the category subfolder for a file name, or "".

func Downloadable

func Downloadable(rawURL string) (ok bool, kind string)

Downloadable reports whether a URL points at a file type worth offering to download (a known category, or an HLS/DASH stream). Used for the clipboard monitor; returns the stream kind ("hls", "dash" or "").

func IsPlaylistURL added in v0.8.9

func IsPlaylistURL(raw string) bool

IsPlaylistURL reports whether raw is a YouTube playlist page URL.

func ParseChecksum

func ParseChecksum(s string) (string, error)

ParseChecksum accepts a hex MD5, SHA-1, SHA-256 or SHA-512, optionally prefixed like "sha256:" or followed by a file name (as in .sha256 files), and returns it normalised. The algorithm is told by its length.

func ParseProxy

func ParseProxy(s string) (string, error)

ParseProxy checks a proxy setting and returns it normalised.

func SafeName

func SafeName(name string) string

safeName makes name (from a web server, so untrusted) a plain file name inside the download folder: no path separators or "..", no Windows device names, no trailing dots or spaces, and short enough for Windows. SafeName cleans a file name the way downloads are saved (see safeName).

func Transient

func Transient(err error) bool

Transient reports whether err is worth retrying later: the network dropped or the server had a temporary problem. A missing file, a refused link or a full disk is not.

func VideoPage

func VideoPage(raw string) bool

VideoPage identifies individual videos, never a site's home feed or playlist.

func VideoTool added in v0.8.7

func VideoTool(name string) (string, error)

VideoTool locates an external helper (ffmpeg, yt-dlp, deno) beside Velo, on the process PATH, in the live OS PATH registry, or in common package manager directories.

Types

type ChecksumError

type ChecksumError struct{ Algo, Want, Got string }

ChecksumError means the finished file doesn't match the expected checksum.

func (*ChecksumError) Error

func (e *ChecksumError) Error() string

type DiskFullError

type DiskFullError struct {
	Need, Free int64
	Dir        string
}

errBusy means the server refused another connection (429/503). DiskFullError means the file is bigger than the space left on the drive.

func (*DiskFullError) Error

func (e *DiskFullError) Error() string

type Download

type Download struct {
	ID       int
	Req      Request
	Path     string
	Total    int64 // -1 if unknown
	Ranged   bool
	Done     atomic.Int64
	Status   string // queued, downloading, paused, done, error
	Err      error
	Verified bool // matched Req.Checksum
	// contains filtered or unexported fields
}

func FindPaused

func FindPaused(dir string) []*Download

FindPaused lists the paused downloads in dir.

func Load

func Load(stateFile string) (*Download, error)

Load restores a paused download from its .part.json file.

func (*Download) Connections

func (d *Download) Connections() int

Connections reports how many connections are currently downloading.

func (*Download) Info

func (d *Download) Info() (path string, total int64)

Info returns the file path and total size (-1 if unknown); safe while running.

func (*Download) Progress

func (d *Download) Progress() float64

Progress returns percent complete (0 if unknown, 100 once done).

func (*Download) ProgressWith added in v0.8.10

func (d *Download) ProgressWith(status string, total int64) float64

ProgressWith returns percent complete given an already fetched status and total size.

func (*Download) QueueID

func (d *Download) QueueID() string

QueueID is the download's named queue ("" = the main queue).

func (*Download) RemainingGaps added in v0.8.8

func (d *Download) RemainingGaps() [][2]float64

RemainingGaps returns unfetched [startPct, widthPct] intervals for a multi-part download once bytes have started arriving.

func (*Download) SetQueue

func (d *Download) SetQueue(q string)

SetQueue moves the download to a named queue ("" = the main queue).

func (*Download) SetRequest

func (d *Download) SetRequest(r Request)

SetRequest replaces the download's request (a refreshed link) while it isn't running; progress and the file are kept.

func (*Download) SetStatus

func (d *Download) SetStatus(s string)

SetStatus sets the status of a download that isn't running (e.g. queued).

func (*Download) State

func (d *Download) State() (string, error)

State returns the status and last error; safe to call while Run is active.

func (*Download) StateInfoQueue added in v0.8.10

func (d *Download) StateInfoQueue() (status string, err error, path string, total int64, queueID string)

StateInfoQueue returns status, last error, path, total size, and queue ID in a single lock acquisition.

type Engine

type Engine struct {
	Client *http.Client
	Limit  *Limiter // shared speed limit; nil = unlimited
	// contains filtered or unexported fields
}

func New

func New(dir string) *Engine

func (*Engine) Dir

func (e *Engine) Dir() string

Dir is the folder new downloads are saved to. Downloads already started keep their own path when it changes.

func (*Engine) FolderFor

func (e *Engine) FolderFor(name string) string

FolderFor is the folder a new download named name goes to by default.

func (*Engine) Probe

func (e *Engine) Probe(ctx context.Context, r Request) (Info, error)

Probe asks the server about r.URL with a one-byte range request.

func (*Engine) Run

func (e *Engine) Run(ctx context.Context, d *Download) error

Run downloads (or resumes) d. Cancelling ctx pauses it: progress is saved and Run returns context.Canceled with Status "paused".

func (*Engine) SegmentsDefault

func (e *Engine) SegmentsDefault() int

SegmentsDefault is the default number of connections per download.

func (*Engine) SetDir

func (e *Engine) SetDir(d string)

func (*Engine) SetProxy

func (e *Engine) SetProxy(s string)

SetProxy changes the proxy for new connections (see ParseProxy).

func (*Engine) SetSegments

func (e *Engine) SetSegments(n int)

SetSegments sets the default number of connections per download (1-32).

func (*Engine) SetSortByType

func (e *Engine) SetSortByType(on bool)

SetSortByType turns category subfolders on or off for new downloads.

func (*Engine) VideoFilename added in v0.8.10

func (e *Engine) VideoFilename(ctx context.Context, r Request) (string, error)

VideoFilename resolves the selected video's metadata using the same credentials and proxy as the download. Browser tab titles may describe a search or feed.

type Info

type Info struct {
	Name      string `json:"name"`
	Size      int64  `json:"size"`      // -1 if unknown
	Resumable bool   `json:"resumable"` // server supports byte ranges
	Category  string `json:"category"`
	Kind      string `json:"kind"` // "", "hls" or "dash"
}

Info describes a link before it's downloaded (for the Add Download dialog).

type Limiter

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

Limiter is a shared bandwidth budget for all downloads (a global speed limit). The rate can be changed at any time; 0 means unlimited.

func (*Limiter) Rate

func (l *Limiter) Rate() int64

func (*Limiter) SetRate

func (l *Limiter) SetRate(bytesPerSec int64)

func (*Limiter) Wait

func (l *Limiter) Wait(ctx context.Context, n int) error

Wait blocks until n bytes fit in the budget or ctx ends.

type PlaylistEntry added in v0.8.9

type PlaylistEntry struct {
	URL   string `json:"url"`
	Title string `json:"title"`
}

PlaylistEntry is one video inside an expanded playlist.

func ExpandPlaylist added in v0.8.9

func ExpandPlaylist(ctx context.Context, rawURL string) (string, []PlaylistEntry, error)

ExpandPlaylist uses yt-dlp --flat-playlist to list the videos in a playlist.

type Request

type Request struct {
	URL, Referrer, Cookies, UserAgent, Filename string
	Kind                                        string // "" = file, "hls"/.m3u8, "dash"/.mpd, "page"/yt-dlp
	Title                                       string // page/video title, used to name videos
	Dir                                         string `json:",omitempty"` // save here instead of the default/category folder
	Segments                                    int    `json:",omitempty"` // connections for this download (0 = engine default)
	User, Pass                                  string `json:",omitempty"` // HTTP login for sites that ask for one
	Checksum                                    string `json:",omitempty"`
	Queue                                       string `json:",omitempty"` // named queue ID; "" = the main queue // expected MD5/SHA-1/SHA-256/SHA-512 (hex), checked when done
	Format                                      string `json:",omitempty"` // video quality: "" (best), "1080p", "720p", "480p", "audio"
}

type Segment

type Segment struct {
	Pos int64 `json:"pos"`
	End int64 `json:"end"`
	// contains filtered or unexported fields
}

Segment is the byte range [Pos, End] still to fetch. Guarded by Download.mu.

type StatusError

type StatusError struct {
	Code int
	Msg  string
}

StatusError is an HTTP error response.

func (*StatusError) Error

func (e *StatusError) Error() string

Jump to

Keyboard shortcuts

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