warpcli

package
v1.4.3 Latest Latest
Warning

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

Go to latest
Published: Mar 12, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SchemeUnix = "unix"
	SchemeTCP  = "tcp"
	SchemePipe = "pipe"
)

Supported URI schemes

View Source
const VersionCheckEnv = "WARPDL_SUPPRESS_VERSION_CHECK"

VersionCheckEnv is the environment variable name used to suppress version mismatch warnings. Set to any non-empty value to disable warnings (useful for scripts and CI).

Variables

View Source
var (
	ErrEmptyURI          = errors.New("daemon URI cannot be empty")
	ErrUnsupportedScheme = errors.New("unsupported URI scheme")
	ErrInvalidPath       = errors.New("invalid path in URI")
	ErrPipeNotSupported  = errors.New("pipe:// scheme only supported on Windows")
	ErrUnixNotSupported  = errors.New("unix:// scheme not supported on Windows")
)

Errors

View Source
var ErrDisconnect error = errors.New("disconnect")

ErrDisconnect is a sentinel error returned by handlers to signal that the client should disconnect from the daemon.

Functions

func ReadForTesting added in v1.3.27

func ReadForTesting(conn net.Conn) ([]byte, error)

ReadForTesting exposes the read function for testing purposes.

func WriteForTesting added in v1.3.27

func WriteForTesting(conn net.Conn, data []byte) error

WriteForTesting exposes the write function for testing purposes.

Types

type Client

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

Client manages communication with the WarpDL daemon over IPC. It provides methods to invoke daemon operations and listen for asynchronous updates such as download progress notifications. The client automatically selects the best transport available: - Unix/Linux: Unix socket with TCP fallback - Windows: Named pipe with TCP fallback

func NewClient

func NewClient() (*Client, error)

NewClient creates a new client connection to the WarpDL daemon. It connects to the daemon using platform-specific IPC and returns a ready-to-use client. If the daemon is not running, it will be automatically spawned. Returns an error if the daemon cannot be started or connection fails.

func NewClientForTesting added in v1.3.27

func NewClientForTesting(conn net.Conn) *Client

NewClientForTesting creates a Client with a custom connection for testing purposes. This allows tests to inject mock connections without needing a daemon.

func NewClientWithURI added in v1.3.22

func NewClientWithURI(rawURI string) (*Client, error)

NewClientWithURI creates a client using an explicit daemon URI. Unlike NewClient(), this does NOT spawn a daemon - it assumes the daemon exists. The URI should be in one of these formats:

  • unix:///absolute/path/to/socket
  • tcp://host:port (or tcp://host for default port 3849)
  • pipe://name (Windows only)

Returns an error if the URI is invalid or connection fails.

func (*Client) ActivateExtension

func (c *Client) ActivateExtension(extensionId string) (*common.ExtensionInfo, error)

ActivateExtension enables a previously deactivated extension. The extensionId identifies the extension to activate. Returns extension metadata on success or an error if activation fails.

func (*Client) AddExtension

func (c *Client) AddExtension(path string) (*common.ExtensionInfo, error)

AddExtension installs a new extension from the specified path. The path should point to a valid extension package. Returns extension metadata on success or an error if installation fails.

func (*Client) AddHandler

func (c *Client) AddHandler(t common.UpdateType, h Handler)

AddHandler registers a handler for the specified update type. Multiple handlers can be registered for the same update type and will be called in the order they were added.

func (*Client) AttachDownload

func (c *Client) AttachDownload(downloadId string) (*common.DownloadResponse, error)

AttachDownload attaches the client to an existing download to receive progress updates. The downloadId identifies the download to attach to. Returns download metadata on success or an error if attachment fails.

func (*Client) CheckVersionMismatch added in v1.3.1

func (c *Client) CheckVersionMismatch(expectedVersion string)

CheckVersionMismatch checks if the daemon version matches the expected CLI version. If there's a mismatch, it prints a warning to stderr but does not block execution. This function should be called after creating a new client to warn users about potential compatibility issues.

Set WARPDL_SUPPRESS_VERSION_CHECK environment variable to suppress warnings.

func (*Client) Close added in v1.3.11

func (c *Client) Close() error

Close closes the client's connection to the daemon. This should be called when the client is no longer needed, especially if Listen() will not be called. Safe to call multiple times (subsequent calls return an error but have no effect).

func (*Client) DeactivateExtension

func (c *Client) DeactivateExtension(extensionId string) (*common.ExtensionName, error)

DeactivateExtension disables an installed extension without uninstalling it. The extensionId identifies the extension to deactivate. Returns the extension name on success or an error if deactivation fails.

func (*Client) DeleteExtension

func (c *Client) DeleteExtension(extensionId string) (*common.ExtensionName, error)

DeleteExtension uninstalls an extension from the daemon. The extensionId identifies the extension to remove. Returns the extension name on success or an error if deletion fails.

func (*Client) Disconnect

func (c *Client) Disconnect()

Disconnect signals the client to stop listening for updates. The Listen method will return after the current update is processed.

func (*Client) Download

func (c *Client) Download(url, fileName, downloadDirectory string, opts *DownloadOpts) (*common.DownloadResponse, error)

Download initiates a new download from the specified URL. The fileName parameter specifies the output file name, and downloadDirectory specifies where to save the file. Pass nil for opts to use default settings. Returns download metadata on success or an error if the download cannot be started.

func (*Client) Flush

func (c *Client) Flush(downloadId string) (bool, error)

Flush removes a completed or failed download from the manager. The downloadId identifies the download to flush. Returns true if the download was successfully removed, or an error if the operation fails.

func (*Client) GetDaemonVersion added in v1.3.1

func (c *Client) GetDaemonVersion() (*common.VersionResponse, error)

GetDaemonVersion retrieves the version information from the running daemon. This is useful for detecting version mismatches between the CLI and daemon. Returns the daemon's version, commit hash, and build type.

func (*Client) GetExtension

func (c *Client) GetExtension(extensionId string) (*common.ExtensionInfo, error)

GetExtension retrieves metadata for an installed extension. The extensionId identifies the extension to retrieve. Returns extension metadata on success or an error if the extension is not found.

func (*Client) List

func (c *Client) List(opts *ListOpts) (*common.ListResponse, error)

List retrieves a list of downloads from the daemon. Pass nil for opts to use default settings (exclude hidden, include metadata). Returns a list of downloads or an error if the operation fails.

func (*Client) ListExtension

func (c *Client) ListExtension(all bool) (*[]common.ExtensionInfoShort, error)

ListExtension retrieves a list of installed extensions. If all is true, includes deactivated extensions; otherwise only active extensions are returned. Returns a list of extension summaries or an error.

func (*Client) Listen

func (c *Client) Listen() (err error)

Listen starts the client's event loop to receive updates from the daemon. It blocks until Disconnect is called or an error occurs. Updates received are dispatched to registered handlers based on their update type. Returns an error if reading from the connection or processing updates fails.

func (*Client) QueueMove added in v1.3.36

func (c *Client) QueueMove(hash string, position int) error

QueueMove moves a queued download to a new position in the waiting queue. The hash identifies the download to move, and position is the target 0-indexed position.

func (*Client) QueuePause added in v1.3.36

func (c *Client) QueuePause() error

QueuePause pauses the download queue, preventing new downloads from auto-starting.

func (*Client) QueueResume added in v1.3.36

func (c *Client) QueueResume() error

QueueResume resumes the download queue, allowing waiting downloads to start.

func (*Client) QueueStatus added in v1.3.36

func (c *Client) QueueStatus() (*common.QueueStatusResponse, error)

QueueStatus returns the current queue status including active and waiting downloads.

func (*Client) RemoveHandler

func (c *Client) RemoveHandler(t common.UpdateType)

RemoveHandler removes all handlers registered for the specified update type.

func (*Client) Resume

func (c *Client) Resume(downloadId string, opts *ResumeOpts) (*common.ResumeResponse, error)

Resume resumes a previously paused or interrupted download. The downloadId identifies the download to resume. Pass nil for opts to use the settings from the original download. Returns download metadata on success or an error if the download cannot be resumed.

func (*Client) StopDownload

func (c *Client) StopDownload(downloadId string) (bool, error)

StopDownload stops an active download. The downloadId identifies the download to stop. Returns true if the download was successfully stopped, or an error if the operation fails.

type DaemonURI added in v1.3.22

type DaemonURI struct {
	Scheme  string // "unix", "tcp", or "pipe"
	Address string // Full address for dial
}

DaemonURI represents a parsed daemon connection URI.

func ParseDaemonURI added in v1.3.22

func ParseDaemonURI(rawURI string) (*DaemonURI, error)

ParseDaemonURI parses a daemon URI string into a DaemonURI struct.

type Dispatcher

type Dispatcher struct {
	Handlers map[common.UpdateType][]Handler
	// contains filtered or unexported fields
}

Dispatcher routes incoming daemon updates to their registered handlers. It maintains a thread-safe map of handlers keyed by update type.

func (*Dispatcher) AddHandler

func (d *Dispatcher) AddHandler(t common.UpdateType, h Handler)

AddHandler registers a handler for the specified update type. Multiple handlers can be registered for the same update type and will be called in the order they were added when an update of that type arrives.

func (*Dispatcher) RemoveHandler

func (d *Dispatcher) RemoveHandler(t common.UpdateType)

RemoveHandler removes all handlers registered for the specified update type.

type DownloadOpts

type DownloadOpts struct {
	// Headers specifies custom HTTP headers to include in download requests.
	Headers warplib.Headers `json:"headers,omitempty"`
	// ForceParts forces the download to use parts even if the server does not
	// advertise support for range requests.
	ForceParts bool `json:"force_parts,omitempty"`
	// MaxConnections limits the maximum number of concurrent connections.
	MaxConnections int32 `json:"max_connections,omitempty"`
	// MaxSegments limits the maximum number of download segments.
	MaxSegments int32 `json:"max_segments,omitempty"`
	// ChildHash is used internally for child downloads in batch operations.
	ChildHash string `json:"child_hash,omitempty"`
	// IsHidden marks the download as hidden from the default list view.
	IsHidden bool `json:"is_hidden,omitempty"`
	// IsChildren indicates this is a child download of a parent batch.
	IsChildren bool `json:"is_children,omitempty"`
	// Overwrite allows replacing an existing file at the destination path.
	Overwrite bool `json:"overwrite,omitempty"`
	// Proxy specifies the proxy server URL for this download.
	Proxy string `json:"proxy,omitempty"`
	// Timeout specifies the per-request timeout in seconds.
	// 0 means no timeout.
	Timeout int `json:"timeout,omitempty"`
	// MaxRetries specifies maximum retry attempts for transient errors.
	// 0 means unlimited retries.
	MaxRetries int `json:"max_retries,omitempty"`
	// RetryDelay specifies the base delay between retries in milliseconds.
	RetryDelay int `json:"retry_delay,omitempty"`
	// SpeedLimit specifies the maximum download speed (e.g., "1MB", "512KB", or raw bytes).
	// If empty or "0", no limit is applied.
	SpeedLimit string `json:"speed_limit,omitempty"`
	// DisableWorkStealing disables dynamic work stealing where fast parts
	// take over remaining work from slow adjacent parts.
	DisableWorkStealing bool `json:"disable_work_stealing,omitempty"`
	// Priority specifies the queue priority (0=low, 1=normal, 2=high).
	// Defaults to normal if not specified.
	Priority int `json:"priority,omitempty"`
	// SSHKeyPath specifies a custom SSH private key file path for SFTP downloads.
	// If empty, default SSH key paths (~/.ssh/id_ed25519, ~/.ssh/id_rsa) are tried.
	SSHKeyPath string `json:"ssh_key_path,omitempty"`
	// StartAt specifies an absolute start time in "YYYY-MM-DD HH:MM" format.
	// Empty means start immediately.
	StartAt string `json:"start_at,omitempty"`
	// CookiesFrom specifies the cookie source: file path, "auto", or "".
	// Empty means no cookie import. "auto" triggers browser auto-detection.
	CookiesFrom string `json:"cookies_from,omitempty"`
	// Schedule specifies a 5-field cron expression for recurring downloads
	// (e.g., "0 2 * * *" = daily at 2 AM). May be combined with StartAt or
	// StartIn to delay the first occurrence. Empty means no recurring schedule.
	Schedule string `json:"schedule,omitempty"`
}

DownloadOpts contains optional parameters for initiating a new download.

type DownloadingHandler

type DownloadingHandler struct {
	Action   common.DownloadingAction
	Callback func(*common.DownloadingResponse) error
}

DownloadingHandler processes download progress updates from the daemon. It filters updates by action type and invokes a callback for matching updates.

func NewDownloadingHandler

func NewDownloadingHandler(action common.DownloadingAction, callback func(*common.DownloadingResponse) error) *DownloadingHandler

NewDownloadingHandler creates a new handler for download progress updates. The action parameter filters updates to only those matching the specified downloading action; pass an empty string to receive all actions. The callback is invoked for each matching update.

func (*DownloadingHandler) Handle

func (h *DownloadingHandler) Handle(m json.RawMessage) error

Handle processes a raw JSON download progress message. It unmarshals the message, checks if it matches the configured action filter, and invokes the callback if applicable. Returns an error if unmarshaling fails or if the callback returns an error.

type Handler

type Handler interface {
	Handle(json.RawMessage) error
}

Handler defines the interface for processing daemon updates. Implementations receive raw JSON messages and are responsible for unmarshaling and processing them appropriately.

type ListOpts

type ListOpts common.ListParams

ListOpts contains optional parameters for listing downloads. It is an alias for common.ListParams.

type Request

type Request struct {
	Method  common.UpdateType `json:"method"`
	Message any               `json:"message,omitempty"`
}

Request represents a JSON-RPC style request sent from the client to the daemon. It contains the method name and an optional message payload.

type Response

type Response struct {
	Ok     bool    `json:"ok"`
	Error  string  `json:"error,omitempty"`
	Update *Update `json:"update,omitempty"`
}

Response represents a JSON-RPC style response received from the daemon. It indicates success or failure and contains an optional update payload.

type ResumeOpts

type ResumeOpts struct {
	// Headers specifies custom HTTP headers to include in download requests.
	Headers warplib.Headers `json:"headers,omitempty"`
	// ForceParts forces the download to use parts even if the server does not
	// advertise support for range requests.
	ForceParts bool `json:"force_parts,omitempty"`
	// MaxConnections limits the maximum number of concurrent connections.
	MaxConnections int32 `json:"max_connections,omitempty"`
	// MaxSegments limits the maximum number of download segments.
	MaxSegments int32 `json:"max_segments,omitempty"`
	// Proxy specifies the proxy server URL for resuming this download.
	Proxy string `json:"proxy,omitempty"`
	// Timeout specifies the per-request timeout in seconds.
	// 0 means no timeout.
	Timeout int `json:"timeout,omitempty"`
	// MaxRetries specifies maximum retry attempts for transient errors.
	// 0 means unlimited retries.
	MaxRetries int `json:"max_retries,omitempty"`
	// RetryDelay specifies the base delay between retries in milliseconds.
	RetryDelay int `json:"retry_delay,omitempty"`
	// SpeedLimit specifies the maximum download speed (e.g., "1MB", "512KB", or raw bytes).
	// If empty or "0", no limit is applied.
	SpeedLimit string `json:"speed_limit,omitempty"`
}

ResumeOpts contains optional parameters for resuming a paused download.

type Update

type Update struct {
	Type    common.UpdateType `json:"type"`
	Message json.RawMessage   `json:"message"`
}

Update represents an asynchronous update received from the daemon. It contains the update type for routing and a raw JSON message payload.

Jump to

Keyboard shortcuts

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