2026-03-28 11:29:42 +01:00
|
|
|
package cmd
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"fmt"
|
|
|
|
|
"log"
|
|
|
|
|
"os"
|
|
|
|
|
"os/signal"
|
|
|
|
|
"strings"
|
|
|
|
|
"syscall"
|
|
|
|
|
"time"
|
|
|
|
|
|
|
|
|
|
"github.com/fatih/color"
|
|
|
|
|
"github.com/spf13/cobra"
|
2026-03-30 13:06:07 +02:00
|
|
|
"github.com/torrentclaw/unarr/internal/agent"
|
|
|
|
|
"github.com/torrentclaw/unarr/internal/engine"
|
|
|
|
|
"github.com/torrentclaw/unarr/internal/parser"
|
2026-03-28 11:29:42 +01:00
|
|
|
)
|
|
|
|
|
|
test: add comprehensive test suite for engine, agent and cmd packages
- Refactor download.go and stream.go with downloadDeps/streamDeps structs
for dependency injection, enabling unit testing without real I/O
- download_test.go: 15 tests — input validation, mock downloaders, method
selection, cobra Args, deadlock detection
- stream_test.go: input validation, noOpen flag, engine error handling
- client_test.go: context cancellation, timeout, full Sync roundtrip,
watch-progress and HTTP error unwrapping
- sync_test.go: TriggerSync on watching transition, adjustInterval
- torrent_test.go: TorrentDownloader lifecycle without network
- stream_server_test.go: HTTP server lifecycle, SetFile/ClearFile,
concurrent requests, Shutdown releases port, content-type
- manager_integration_test.go: full pipeline — success, torrent→debrid
fallback, all-fail, multi-concurrent, ForceStart, OnTaskDone,
recent-finished drain, cancel mid-download, organize
- usenet_test.go: Cancel/Pause race regression test (run with -race)
- daemon_test.go: isAllowedStreamPath table tests
- CI: split coverage gate to engine+agent only (50% threshold); cmd
coverage still reported but not gated (interactive UI commands)
- lefthook: add pre-push hook with go test -race -count=1 -timeout=120s
2026-04-08 23:36:00 +02:00
|
|
|
// downloadDeps agrupa las funciones constructoras usadas por runDownload.
|
|
|
|
|
// Pueden sobreescribirse en tests para inyectar mocks.
|
|
|
|
|
type downloadDeps struct {
|
|
|
|
|
newTorrentDl func(cfg engine.TorrentConfig) (engine.Downloader, error)
|
|
|
|
|
newDebridDl func() engine.Downloader
|
|
|
|
|
newAgentClient func(url, key, ua string) *agent.Client
|
|
|
|
|
newManager func(cfg engine.ManagerConfig, reporter *engine.ProgressReporter, dls ...engine.Downloader) *engine.Manager
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var defaultDownloadDeps = downloadDeps{
|
|
|
|
|
newTorrentDl: func(cfg engine.TorrentConfig) (engine.Downloader, error) {
|
|
|
|
|
return engine.NewTorrentDownloader(cfg)
|
|
|
|
|
},
|
|
|
|
|
newDebridDl: func() engine.Downloader {
|
|
|
|
|
return engine.NewDebridDownloader()
|
|
|
|
|
},
|
|
|
|
|
newAgentClient: agent.NewClient,
|
|
|
|
|
newManager: engine.NewManager,
|
|
|
|
|
}
|
|
|
|
|
|
2026-03-28 11:29:42 +01:00
|
|
|
func newDownloadCmd() *cobra.Command {
|
|
|
|
|
var method string
|
|
|
|
|
|
|
|
|
|
cmd := &cobra.Command{
|
|
|
|
|
Use: "download <info_hash|magnet>",
|
|
|
|
|
Short: "Download a torrent (one-shot, no daemon needed)",
|
|
|
|
|
Long: `Download a specific torrent by info hash or magnet link.
|
docs: improve CLI help, shell completion, and README
- Add command groups (Getting Started, Search, Downloads, Daemon, System)
- Add shell completion command (bash, zsh, fish, powershell)
- Add flag completions for --type, --quality, --sort, --lang, --genre,
--country, --method, --player
- Improve Long descriptions and Examples for all commands
- Split doctor disk check into platform-specific files (Unix/Windows)
- Validate infoHash length before truncating (prevent panic)
- Fix references to non-existent 'unarr daemon start' command
- Move stats command to System & Diagnostics group
- Rewrite README with complete documentation, correct config format
(toml not yaml), all commands, shell completion section
2026-03-28 21:36:27 +01:00
|
|
|
|
|
|
|
|
This is a standalone download that does not require the daemon to be running.
|
|
|
|
|
Useful for quick one-off downloads. The file is saved to your configured
|
|
|
|
|
download directory. Press Ctrl+C to cancel.
|
|
|
|
|
|
|
|
|
|
For managed downloads (queue, progress tracking, web dashboard), use the
|
|
|
|
|
daemon instead: 'unarr start'.`,
|
2026-03-28 11:29:42 +01:00
|
|
|
Example: ` unarr download abc123def456abc123def456abc123def456abc1
|
|
|
|
|
unarr download "magnet:?xt=urn:btih:..." --method torrent`,
|
|
|
|
|
Args: cobra.ExactArgs(1),
|
|
|
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
|
|
|
return runDownload(args[0], method)
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
|
docs: improve CLI help, shell completion, and README
- Add command groups (Getting Started, Search, Downloads, Daemon, System)
- Add shell completion command (bash, zsh, fish, powershell)
- Add flag completions for --type, --quality, --sort, --lang, --genre,
--country, --method, --player
- Improve Long descriptions and Examples for all commands
- Split doctor disk check into platform-specific files (Unix/Windows)
- Validate infoHash length before truncating (prevent panic)
- Fix references to non-existent 'unarr daemon start' command
- Move stats command to System & Diagnostics group
- Rewrite README with complete documentation, correct config format
(toml not yaml), all commands, shell completion section
2026-03-28 21:36:27 +01:00
|
|
|
cmd.Flags().StringVar(&method, "method", "torrent", "download method: torrent, debrid, usenet")
|
|
|
|
|
cmd.RegisterFlagCompletionFunc("method", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
|
|
|
|
return []string{"torrent\tBitTorrent P2P", "debrid\tReal-Debrid / AllDebrid", "usenet\tUsenet (requires Pro)"}, cobra.ShellCompDirectiveNoFileComp
|
|
|
|
|
})
|
2026-03-28 11:29:42 +01:00
|
|
|
|
|
|
|
|
return cmd
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func runDownload(input, method string) error {
|
test: add comprehensive test suite for engine, agent and cmd packages
- Refactor download.go and stream.go with downloadDeps/streamDeps structs
for dependency injection, enabling unit testing without real I/O
- download_test.go: 15 tests — input validation, mock downloaders, method
selection, cobra Args, deadlock detection
- stream_test.go: input validation, noOpen flag, engine error handling
- client_test.go: context cancellation, timeout, full Sync roundtrip,
watch-progress and HTTP error unwrapping
- sync_test.go: TriggerSync on watching transition, adjustInterval
- torrent_test.go: TorrentDownloader lifecycle without network
- stream_server_test.go: HTTP server lifecycle, SetFile/ClearFile,
concurrent requests, Shutdown releases port, content-type
- manager_integration_test.go: full pipeline — success, torrent→debrid
fallback, all-fail, multi-concurrent, ForceStart, OnTaskDone,
recent-finished drain, cancel mid-download, organize
- usenet_test.go: Cancel/Pause race regression test (run with -race)
- daemon_test.go: isAllowedStreamPath table tests
- CI: split coverage gate to engine+agent only (50% threshold); cmd
coverage still reported but not gated (interactive UI commands)
- lefthook: add pre-push hook with go test -race -count=1 -timeout=120s
2026-04-08 23:36:00 +02:00
|
|
|
return runDownloadWithDeps(input, method, defaultDownloadDeps)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func runDownloadWithDeps(input, method string, deps downloadDeps) error {
|
2026-03-28 11:29:42 +01:00
|
|
|
cfg := loadConfig()
|
|
|
|
|
bold := color.New(color.Bold)
|
|
|
|
|
green := color.New(color.FgGreen)
|
|
|
|
|
|
|
|
|
|
// Parse input
|
|
|
|
|
parsed := parser.Parse(input)
|
|
|
|
|
infoHash := parsed.InfoHash
|
|
|
|
|
if infoHash == "" {
|
|
|
|
|
// Treat as info hash directly if 40 hex chars
|
|
|
|
|
input = strings.TrimSpace(input)
|
|
|
|
|
if len(input) == 40 {
|
|
|
|
|
infoHash = strings.ToLower(input)
|
|
|
|
|
} else {
|
|
|
|
|
return fmt.Errorf("invalid input: provide a 40-char info hash or magnet URI")
|
|
|
|
|
}
|
|
|
|
|
}
|
docs: improve CLI help, shell completion, and README
- Add command groups (Getting Started, Search, Downloads, Daemon, System)
- Add shell completion command (bash, zsh, fish, powershell)
- Add flag completions for --type, --quality, --sort, --lang, --genre,
--country, --method, --player
- Improve Long descriptions and Examples for all commands
- Split doctor disk check into platform-specific files (Unix/Windows)
- Validate infoHash length before truncating (prevent panic)
- Fix references to non-existent 'unarr daemon start' command
- Move stats command to System & Diagnostics group
- Rewrite README with complete documentation, correct config format
(toml not yaml), all commands, shell completion section
2026-03-28 21:36:27 +01:00
|
|
|
if len(infoHash) < 40 {
|
|
|
|
|
return fmt.Errorf("invalid info hash: expected 40 characters, got %d", len(infoHash))
|
|
|
|
|
}
|
2026-03-28 11:29:42 +01:00
|
|
|
|
|
|
|
|
outputDir := cfg.Download.Dir
|
|
|
|
|
if outputDir == "" {
|
|
|
|
|
home, _ := os.UserHomeDir()
|
|
|
|
|
outputDir = home
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err := os.MkdirAll(outputDir, 0o755); err != nil {
|
|
|
|
|
return fmt.Errorf("create output dir: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fmt.Println()
|
|
|
|
|
bold.Printf(" Downloading %s...\n", infoHash[:16]+"...")
|
|
|
|
|
fmt.Printf(" Method: %s | Output: %s\n", method, outputDir)
|
|
|
|
|
fmt.Println()
|
|
|
|
|
|
|
|
|
|
// Create torrent downloader
|
test: add comprehensive test suite for engine, agent and cmd packages
- Refactor download.go and stream.go with downloadDeps/streamDeps structs
for dependency injection, enabling unit testing without real I/O
- download_test.go: 15 tests — input validation, mock downloaders, method
selection, cobra Args, deadlock detection
- stream_test.go: input validation, noOpen flag, engine error handling
- client_test.go: context cancellation, timeout, full Sync roundtrip,
watch-progress and HTTP error unwrapping
- sync_test.go: TriggerSync on watching transition, adjustInterval
- torrent_test.go: TorrentDownloader lifecycle without network
- stream_server_test.go: HTTP server lifecycle, SetFile/ClearFile,
concurrent requests, Shutdown releases port, content-type
- manager_integration_test.go: full pipeline — success, torrent→debrid
fallback, all-fail, multi-concurrent, ForceStart, OnTaskDone,
recent-finished drain, cancel mid-download, organize
- usenet_test.go: Cancel/Pause race regression test (run with -race)
- daemon_test.go: isAllowedStreamPath table tests
- CI: split coverage gate to engine+agent only (50% threshold); cmd
coverage still reported but not gated (interactive UI commands)
- lefthook: add pre-push hook with go test -race -count=1 -timeout=120s
2026-04-08 23:36:00 +02:00
|
|
|
torrentDl, err := deps.newTorrentDl(engine.TorrentConfig{
|
2026-03-29 19:09:51 +02:00
|
|
|
DataDir: outputDir,
|
|
|
|
|
MetadataTimeout: 15 * time.Minute,
|
|
|
|
|
StallTimeout: 10 * time.Minute,
|
|
|
|
|
MaxTimeout: 0, // unlimited
|
|
|
|
|
SeedEnabled: false,
|
feat(torrent): act as WebTorrent peer for browser ↔ unarr P2P streaming
Wires anacrolix/torrent's built-in webtorrent package so a browser
running webtorrent.js can fetch pieces from this CLI via WebRTC data
channels. The daemon stays the seeder; we never relay bytes through
TorrentClaw infrastructure — same legal posture as today.
Changes:
- internal/config: new [downloads.webrtc] section
(enabled/trackers/stun_servers/turn_servers/turn_user/turn_pass).
Disabled by default, opt-in via config.toml. When enabled but
trackers / STUN slices are empty, defaults are reapplied on Load() so
users get a working setup with a single `enabled = true`.
- internal/engine: TorrentConfig gains WebRTCEnabled / WebRTCTrackers
/ ICEServers; NewTorrentDownloader populates ClientConfig.ICEServerList
and forces NoUpload=false when WebRTC is on (browsers can't pull
otherwise). buildMagnet now accepts variadic extra trackers and the
downloader method prepends WSS trackers so anacrolix's
webtorrent.TrackerClient picks them up first.
- internal/engine/webrtc.go: BuildICEServers helper converts the TOML
WebRTCConfig into []webrtc.ICEServer with shared TURN credentials.
- internal/cmd/daemon.go + download.go: pass WebRTC config through to
the engine.
Tests (8 new, all green; full suite 0 lint issues, 0 vet):
- buildMagnet free function: defaults-only, with extras, trim+empty-skip
- downloader method: WebRTC disabled keeps WSS out, enabled prepends them
- BuildICEServers: nil when disabled, STUN-only path, TURN+credentials
- NewTorrentDownloader: full WebRTC-enabled construction (logs WebRTC
peer enabled, magnet contains wss://tracker.torrentclaw.com)
End-to-end smoke (browser ↔ unarr peer transfer) is deferred to a
manual test once tracker.torrentclaw.com WSS is live.
2026-05-06 08:59:58 +02:00
|
|
|
WebRTCEnabled: cfg.Download.WebRTC.Enabled,
|
|
|
|
|
WebRTCTrackers: cfg.Download.WebRTC.Trackers,
|
|
|
|
|
ICEServers: engine.BuildICEServers(cfg.Download.WebRTC),
|
2026-03-28 11:29:42 +01:00
|
|
|
})
|
|
|
|
|
if err != nil {
|
|
|
|
|
return fmt.Errorf("create downloader: %w", err)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Create a dummy reporter (no API reporting for one-shot)
|
|
|
|
|
reporter := engine.NewProgressReporter(
|
test: add comprehensive test suite for engine, agent and cmd packages
- Refactor download.go and stream.go with downloadDeps/streamDeps structs
for dependency injection, enabling unit testing without real I/O
- download_test.go: 15 tests — input validation, mock downloaders, method
selection, cobra Args, deadlock detection
- stream_test.go: input validation, noOpen flag, engine error handling
- client_test.go: context cancellation, timeout, full Sync roundtrip,
watch-progress and HTTP error unwrapping
- sync_test.go: TriggerSync on watching transition, adjustInterval
- torrent_test.go: TorrentDownloader lifecycle without network
- stream_server_test.go: HTTP server lifecycle, SetFile/ClearFile,
concurrent requests, Shutdown releases port, content-type
- manager_integration_test.go: full pipeline — success, torrent→debrid
fallback, all-fail, multi-concurrent, ForceStart, OnTaskDone,
recent-finished drain, cancel mid-download, organize
- usenet_test.go: Cancel/Pause race regression test (run with -race)
- daemon_test.go: isAllowedStreamPath table tests
- CI: split coverage gate to engine+agent only (50% threshold); cmd
coverage still reported but not gated (interactive UI commands)
- lefthook: add pre-push hook with go test -race -count=1 -timeout=120s
2026-04-08 23:36:00 +02:00
|
|
|
deps.newAgentClient(cfg.Auth.APIURL, cfg.Auth.APIKey, "unarr/"+Version),
|
2026-03-28 11:29:42 +01:00
|
|
|
5*time.Second,
|
|
|
|
|
)
|
|
|
|
|
|
test: add comprehensive test suite for engine, agent and cmd packages
- Refactor download.go and stream.go with downloadDeps/streamDeps structs
for dependency injection, enabling unit testing without real I/O
- download_test.go: 15 tests — input validation, mock downloaders, method
selection, cobra Args, deadlock detection
- stream_test.go: input validation, noOpen flag, engine error handling
- client_test.go: context cancellation, timeout, full Sync roundtrip,
watch-progress and HTTP error unwrapping
- sync_test.go: TriggerSync on watching transition, adjustInterval
- torrent_test.go: TorrentDownloader lifecycle without network
- stream_server_test.go: HTTP server lifecycle, SetFile/ClearFile,
concurrent requests, Shutdown releases port, content-type
- manager_integration_test.go: full pipeline — success, torrent→debrid
fallback, all-fail, multi-concurrent, ForceStart, OnTaskDone,
recent-finished drain, cancel mid-download, organize
- usenet_test.go: Cancel/Pause race regression test (run with -race)
- daemon_test.go: isAllowedStreamPath table tests
- CI: split coverage gate to engine+agent only (50% threshold); cmd
coverage still reported but not gated (interactive UI commands)
- lefthook: add pre-push hook with go test -race -count=1 -timeout=120s
2026-04-08 23:36:00 +02:00
|
|
|
debridDl := deps.newDebridDl()
|
feat(debrid): add HTTPS downloader for debrid direct URLs
DebridDownloader receives directUrl from the server and downloads via
plain HTTPS with progress reporting, resume (Range), and pause/cancel.
- Add DirectURL, DirectFileName to agent Task and engine Task types
- Implement DebridDownloader: HTTPS download with progress, resume, cancel
- HTTP client with 30s ResponseHeaderTimeout
- Safe shortID helper to prevent slice panic on short IDs
- Validate 416 against Content-Range server size for resume integrity
- Register debridDl in daemon and one-shot download command
- Tests: available, download, resume, cancel, pause, fallback filename,
expired URL (410), unauthorized (401), shutdown, task propagation
2026-03-28 18:09:34 +01:00
|
|
|
|
test: add comprehensive test suite for engine, agent and cmd packages
- Refactor download.go and stream.go with downloadDeps/streamDeps structs
for dependency injection, enabling unit testing without real I/O
- download_test.go: 15 tests — input validation, mock downloaders, method
selection, cobra Args, deadlock detection
- stream_test.go: input validation, noOpen flag, engine error handling
- client_test.go: context cancellation, timeout, full Sync roundtrip,
watch-progress and HTTP error unwrapping
- sync_test.go: TriggerSync on watching transition, adjustInterval
- torrent_test.go: TorrentDownloader lifecycle without network
- stream_server_test.go: HTTP server lifecycle, SetFile/ClearFile,
concurrent requests, Shutdown releases port, content-type
- manager_integration_test.go: full pipeline — success, torrent→debrid
fallback, all-fail, multi-concurrent, ForceStart, OnTaskDone,
recent-finished drain, cancel mid-download, organize
- usenet_test.go: Cancel/Pause race regression test (run with -race)
- daemon_test.go: isAllowedStreamPath table tests
- CI: split coverage gate to engine+agent only (50% threshold); cmd
coverage still reported but not gated (interactive UI commands)
- lefthook: add pre-push hook with go test -race -count=1 -timeout=120s
2026-04-08 23:36:00 +02:00
|
|
|
manager := deps.newManager(engine.ManagerConfig{
|
2026-03-28 11:29:42 +01:00
|
|
|
MaxConcurrent: 1,
|
|
|
|
|
OutputDir: outputDir,
|
|
|
|
|
Organize: engine.OrganizeConfig{
|
|
|
|
|
Enabled: cfg.Organize.Enabled,
|
|
|
|
|
MoviesDir: cfg.Organize.MoviesDir,
|
|
|
|
|
TVShowsDir: cfg.Organize.TVShowsDir,
|
2026-04-05 23:36:01 +02:00
|
|
|
OutputDir: outputDir,
|
2026-03-28 11:29:42 +01:00
|
|
|
},
|
feat(debrid): add HTTPS downloader for debrid direct URLs
DebridDownloader receives directUrl from the server and downloads via
plain HTTPS with progress reporting, resume (Range), and pause/cancel.
- Add DirectURL, DirectFileName to agent Task and engine Task types
- Implement DebridDownloader: HTTPS download with progress, resume, cancel
- HTTP client with 30s ResponseHeaderTimeout
- Safe shortID helper to prevent slice panic on short IDs
- Validate 416 against Content-Range server size for resume integrity
- Register debridDl in daemon and one-shot download command
- Tests: available, download, resume, cancel, pause, fallback filename,
expired URL (410), unauthorized (401), shutdown, task propagation
2026-03-28 18:09:34 +01:00
|
|
|
}, reporter, torrentDl, debridDl)
|
2026-03-28 11:29:42 +01:00
|
|
|
|
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
|
|
// Signal handling
|
|
|
|
|
sigCh := make(chan os.Signal, 1)
|
|
|
|
|
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
|
|
|
|
|
go func() {
|
|
|
|
|
<-sigCh
|
|
|
|
|
fmt.Println("\n Cancelling download...")
|
|
|
|
|
cancel()
|
|
|
|
|
}()
|
|
|
|
|
|
|
|
|
|
// Start progress reporter
|
|
|
|
|
go reporter.Run(ctx)
|
|
|
|
|
|
|
|
|
|
// Submit task
|
|
|
|
|
task := agent.Task{
|
|
|
|
|
ID: "oneshot-" + infoHash[:8],
|
|
|
|
|
InfoHash: infoHash,
|
|
|
|
|
Title: parsed.Name,
|
|
|
|
|
PreferredMethod: method,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
manager.Submit(ctx, task)
|
|
|
|
|
manager.Wait()
|
|
|
|
|
|
|
|
|
|
// Check result
|
|
|
|
|
active := manager.ActiveTasks()
|
|
|
|
|
if len(active) == 0 {
|
|
|
|
|
green.Println(" Download complete!")
|
|
|
|
|
} else {
|
|
|
|
|
for _, t := range active {
|
|
|
|
|
if t.GetStatus() == engine.StatusFailed {
|
|
|
|
|
return fmt.Errorf("download failed: %s", t.ErrorMessage)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Shutdown
|
|
|
|
|
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
|
|
|
defer shutdownCancel()
|
|
|
|
|
manager.Shutdown(shutdownCtx)
|
|
|
|
|
cancel()
|
|
|
|
|
|
|
|
|
|
log.SetOutput(os.Stderr) // suppress cleanup logs
|
|
|
|
|
fmt.Println()
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
}
|