1 // Downloads torrents from the command-line.
16 "github.com/anacrolix/envpprof"
17 "github.com/anacrolix/tagflag"
18 "github.com/anacrolix/torrent"
19 "github.com/anacrolix/torrent/iplist"
20 "github.com/anacrolix/torrent/metainfo"
21 "github.com/anacrolix/torrent/storage"
22 "github.com/dustin/go-humanize"
23 "github.com/gosuri/uiprogress"
24 "golang.org/x/time/rate"
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 {
154 func exitSignalHandlers(client *torrent.Client) {
155 c := make(chan os.Signal, 1)
156 signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
158 log.Printf("close signal received: %+v", <-c)
164 log.SetFlags(log.LstdFlags | log.Lshortfile)
165 tagflag.Parse(&flags)
166 defer envpprof.Stop()
167 clientConfig := torrent.NewDefaultClientConfig()
168 clientConfig.Debug = flags.Debug
169 clientConfig.Seed = flags.Seed
170 if flags.PackedBlocklist != "" {
171 blocklist, err := iplist.MMapPackedFile(flags.PackedBlocklist)
173 log.Fatalf("error loading blocklist: %s", err)
175 defer blocklist.Close()
176 clientConfig.IPBlocklist = blocklist
179 clientConfig.DefaultStorage = storage.NewMMap("")
181 if flags.Addr != nil {
182 clientConfig.SetListenAddr(flags.Addr.String())
184 if flags.UploadRate != -1 {
185 clientConfig.UploadRateLimiter = rate.NewLimiter(rate.Limit(flags.UploadRate), 256<<10)
187 if flags.DownloadRate != -1 {
188 clientConfig.DownloadRateLimiter = rate.NewLimiter(rate.Limit(flags.DownloadRate), 1<<20)
191 client, err := torrent.NewClient(clientConfig)
193 log.Fatalf("error creating client: %s", err)
196 go exitSignalHandlers(client)
198 // Write status on the root path on the default HTTP muxer. This will be
199 // bound to localhost somewhere if GOPPROF is set, thanks to the envpprof
201 http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
202 client.WriteStatus(w)
204 if stdoutAndStderrAreSameFile() {
205 log.SetOutput(progress.Bypass())
209 if client.WaitAll() {
210 log.Print("downloaded ALL the torrents")
212 log.Fatal("y u no complete torrents?!")
221 func outputStats(cl *torrent.Client) {
225 expvar.Do(func(kv expvar.KeyValue) {
226 fmt.Printf("%s: %s\n", kv.Key, kv.Value)
228 cl.WriteStatus(os.Stdout)