1 // Downloads torrents from the command-line.
14 _ "github.com/anacrolix/envpprof"
15 "github.com/anacrolix/tagflag"
16 "github.com/dustin/go-humanize"
17 "github.com/gosuri/uiprogress"
19 "github.com/anacrolix/torrent"
20 "github.com/anacrolix/torrent/metainfo"
21 "github.com/anacrolix/torrent/storage"
24 func resolvedPeerAddrs(ss []string) (ret []torrent.Peer, err error) {
25 for _, s := range ss {
27 addr, err = net.ResolveTCPAddr("tcp", s)
31 ret = append(ret, torrent.Peer{
39 func torrentBar(t torrent.Torrent) {
40 bar := uiprogress.AddBar(1)
42 bar.AppendFunc(func(*uiprogress.Bar) (ret string) {
50 } else if t.BytesCompleted() == t.Info().TotalLength() {
53 return fmt.Sprintf("downloading (%s/%s)", humanize.Bytes(uint64(t.BytesCompleted())), humanize.Bytes(uint64(t.Info().TotalLength())))
56 bar.PrependFunc(func(*uiprogress.Bar) string {
61 bar.Total = int(t.Info().TotalLength())
63 bc := t.BytesCompleted()
65 time.Sleep(time.Second)
70 func addTorrents(client *torrent.Client) {
71 for _, arg := range opts.Torrent {
72 t := func() torrent.Torrent {
73 if strings.HasPrefix(arg, "magnet:") {
74 t, err := client.AddMagnet(arg)
76 log.Fatalf("error adding magnet: %s", err)
80 metaInfo, err := metainfo.LoadFromFile(arg)
82 fmt.Fprintf(os.Stderr, "error loading torrent file %q: %s\n", arg, err)
85 t, err := client.AddTorrent(metaInfo)
93 err := t.AddPeers(func() (ret []torrent.Peer) {
94 for _, ta := range opts.TestPeer {
95 ret = append(ret, torrent.Peer{
113 torrent.Config `name:"Client"`
114 Mmap bool `help:"memory-map torrent data"`
115 TestPeer []*net.TCPAddr `short:"p" help:"addresses of some starting peers"`
116 Torrent []string `type:"pos" arity:"+" help:"torrent file path or magnet uri"`
120 log.SetFlags(log.LstdFlags | log.Lshortfile)
121 tagflag.Parse(&opts, tagflag.SkipBadTypes())
122 clientConfig := opts.Config
124 clientConfig.DefaultStorage = storage.NewMMap("")
127 client, err := torrent.NewClient(&clientConfig)
129 log.Fatalf("error creating client: %s", err)
132 http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
133 client.WriteStatus(w)
137 if client.WaitAll() {
138 log.Print("downloaded ALL the torrents")
140 log.Fatal("y u no complete torrents?!")