FedP2P/cmd/torrent/main.go

111 lines
2.5 KiB
Go
Raw Normal View History

2013-09-26 17:49:15 +08:00
package main
import (
"flag"
"fmt"
2013-09-26 17:49:15 +08:00
"log"
"net"
"net/http"
_ "net/http/pprof"
"os"
"strings"
_ "github.com/anacrolix/envpprof"
2014-06-28 17:38:31 +08:00
"github.com/anacrolix/libtorgo/metainfo"
"github.com/anacrolix/torrent"
2013-09-26 17:49:15 +08:00
)
var (
downloadDir = flag.String("downloadDir", "", "directory to store download torrent data")
testPeer = flag.String("testPeer", "", "bootstrap peer address")
// TODO: Check the default torrent listen port.
2014-11-17 11:21:13 +08:00
listenAddr = flag.String("listenAddr", ":50007", "incoming connection address")
disableTrackers = flag.Bool("disableTrackers", false, "disable trackers")
disableDHT = flag.Bool("disableDHT", false, "disable DHT")
seed = flag.Bool("seed", false, "seed after downloading")
2014-12-01 17:29:56 +08:00
upload = flag.Bool("upload", true, "upload data to peers")
2013-09-26 17:49:15 +08:00
)
2015-03-20 20:18:32 +08:00
func usage() {
fmt.Fprintf(os.Stderr, "Usage: %s [flags] (magnet URI or .torrent file path)...\n", os.Args[0])
os.Stderr.WriteString("Download using the BitTorrent network.\n")
flag.PrintDefaults()
}
2014-08-25 20:14:10 +08:00
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
2015-03-20 20:18:32 +08:00
flag.Usage = usage
2013-09-26 17:49:15 +08:00
flag.Parse()
2014-08-21 16:07:06 +08:00
client, err := torrent.NewClient(&torrent.Config{
DataDir: *downloadDir,
DisableTrackers: *disableTrackers,
2014-08-21 16:07:06 +08:00
ListenAddr: *listenAddr,
2014-12-01 17:29:56 +08:00
NoUpload: !*upload,
NoDHT: *disableDHT,
2014-08-21 16:07:06 +08:00
})
if err != nil {
log.Fatalf("error creating client: %s", err)
}
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
client.WriteStatus(w)
})
2015-03-08 14:28:14 +08:00
defer client.Close()
if flag.NArg() == 0 {
fmt.Fprintln(os.Stderr, "no torrents specified")
return
}
2013-09-26 17:49:15 +08:00
for _, arg := range flag.Args() {
t := func() torrent.Torrent {
if strings.HasPrefix(arg, "magnet:") {
t, err := client.AddMagnet(arg)
if err != nil {
log.Fatalf("error adding magnet: %s", err)
}
return t
} else {
metaInfo, err := metainfo.LoadFromFile(arg)
if err != nil {
log.Fatal(err)
}
t, err := client.AddTorrent(metaInfo)
if err != nil {
log.Fatal(err)
}
return t
}
}()
2014-08-28 08:05:41 +08:00
// client.PrioritizeDataRegion(ih, 0, 999999999)
err := t.AddPeers(func() []torrent.Peer {
if *testPeer == "" {
return nil
}
addr, err := net.ResolveTCPAddr("tcp", *testPeer)
if err != nil {
log.Fatal(err)
}
return []torrent.Peer{{
IP: addr.IP,
Port: addr.Port,
}}
}())
if err != nil {
log.Fatal(err)
}
go func() {
<-t.GotMetainfo
t.DownloadAll()
}()
2013-09-26 17:49:15 +08:00
}
if *seed {
select {}
}
if client.WaitAll() {
2014-08-28 08:05:41 +08:00
log.Print("downloaded ALL the torrents")
} else {
log.Fatal("y u no complete torrents?!")
}
2013-09-26 17:49:15 +08:00
}