1 // Downloads torrents from the command-line.
14 "github.com/anacrolix/torrent/iplist"
16 "github.com/anacrolix/envpprof"
17 "github.com/anacrolix/tagflag"
18 "github.com/dustin/go-humanize"
19 "github.com/gosuri/uiprogress"
20 "golang.org/x/time/rate"
22 "github.com/anacrolix/torrent"
23 "github.com/anacrolix/torrent/metainfo"
24 "github.com/anacrolix/torrent/storage"
27 var progress = uiprogress.New()
29 func torrentBar(t *torrent.Torrent) {
30 bar := progress.AddBar(1)
32 bar.AppendFunc(func(*uiprogress.Bar) (ret string) {
40 } else if t.BytesCompleted() == t.Info().TotalLength() {
43 return fmt.Sprintf("downloading (%s/%s)", humanize.Bytes(uint64(t.BytesCompleted())), humanize.Bytes(uint64(t.Info().TotalLength())))
46 bar.PrependFunc(func(*uiprogress.Bar) string {
51 tl := int(t.Info().TotalLength())
58 bc := t.BytesCompleted()
60 time.Sleep(time.Second)
65 func addTorrents(client *torrent.Client) {
66 for _, arg := range flags.Torrent {
67 t := func() *torrent.Torrent {
68 if strings.HasPrefix(arg, "magnet:") {
69 t, err := client.AddMagnet(arg)
71 log.Fatalf("error adding magnet: %s", err)
74 } else if strings.HasPrefix(arg, "http://") || strings.HasPrefix(arg, "https://") {
75 response, err := http.Get(arg)
77 log.Fatalf("Error downloading torrent file: %s", err)
80 metaInfo, err := metainfo.Load(response.Body)
81 defer response.Body.Close()
83 fmt.Fprintf(os.Stderr, "error loading torrent file %q: %s\n", arg, err)
86 t, err := client.AddTorrent(metaInfo)
91 } else if strings.HasPrefix(arg, "infohash:") {
92 t, _ := client.AddTorrentInfoHash(metainfo.NewHashFromHex(strings.TrimPrefix(arg, "infohash:")))
95 metaInfo, err := metainfo.LoadFromFile(arg)
97 fmt.Fprintf(os.Stderr, "error loading torrent file %q: %s\n", arg, err)
100 t, err := client.AddTorrent(metaInfo)
108 t.AddPeers(func() (ret []torrent.Peer) {
109 for _, ta := range flags.TestPeer {
110 ret = append(ret, torrent.Peer{
125 Mmap bool `help:"memory-map torrent data"`
126 TestPeer []*net.TCPAddr `help:"addresses of some starting peers"`
127 Seed bool `help:"seed after download is complete"`
128 Addr *net.TCPAddr `help:"network listen addr"`
129 UploadRate tagflag.Bytes `help:"max piece bytes to send per second"`
130 DownloadRate tagflag.Bytes `help:"max bytes per second down from peers"`
132 PackedBlocklist string
135 Torrent []string `arity:"+" help:"torrent file path or magnet uri"`
141 func stdoutAndStderrAreSameFile() bool {
142 fi1, _ := os.Stdout.Stat()
143 fi2, _ := os.Stderr.Stat()
144 return os.SameFile(fi1, fi2)
147 func statsEnabled() bool {
148 if flags.Stats == nil {
155 log.SetFlags(log.LstdFlags | log.Lshortfile)
156 tagflag.Parse(&flags)
157 defer envpprof.Stop()
158 clientConfig := torrent.NewDefaultClientConfig()
159 clientConfig.Debug = flags.Debug
160 clientConfig.Seed = flags.Seed
161 if flags.PackedBlocklist != "" {
162 blocklist, err := iplist.MMapPackedFile(flags.PackedBlocklist)
164 log.Fatalf("error loading blocklist: %s", err)
166 defer blocklist.Close()
167 clientConfig.IPBlocklist = blocklist
170 clientConfig.DefaultStorage = storage.NewMMap("")
172 if flags.Addr != nil {
173 clientConfig.SetListenAddr(flags.Addr.String())
175 if flags.UploadRate != -1 {
176 clientConfig.UploadRateLimiter = rate.NewLimiter(rate.Limit(flags.UploadRate), 256<<10)
178 if flags.DownloadRate != -1 {
179 clientConfig.DownloadRateLimiter = rate.NewLimiter(rate.Limit(flags.DownloadRate), 1<<20)
182 client, err := torrent.NewClient(clientConfig)
184 log.Fatalf("error creating client: %s", err)
187 // Write status on the root path on the default HTTP muxer. This will be
188 // bound to localhost somewhere if GOPPROF is set, thanks to the envpprof
190 http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
191 client.WriteStatus(w)
193 if stdoutAndStderrAreSameFile() {
194 log.SetOutput(progress.Bypass())
198 if client.WaitAll() {
199 log.Print("downloaded ALL the torrents")
201 log.Fatal("y u no complete torrents?!")
210 func outputStats(cl *torrent.Client) {
214 expvar.Do(func(kv expvar.KeyValue) {
215 fmt.Printf("%s: %s\n", kv.Key, kv.Value)
217 cl.WriteStatus(os.Stdout)