forked from anacrolix/torrent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
187 lines (166 loc) · 4.1 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
// Downloads torrents from the command-line.
package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
_ "net/http/pprof"
"os"
"strings"
"time"
_ "github.com/anacrolix/envpprof"
"github.com/anacrolix/missinggo"
"github.com/dustin/go-humanize"
"github.com/jessevdk/go-flags"
"github.com/anacrolix/torrent"
"github.com/anacrolix/torrent/metainfo"
)
// fmt.Fprintf(os.Stderr, "Usage: %s \n", os.Args[0])
func resolvedPeerAddrs(ss []string) (ret []torrent.Peer, err error) {
for _, s := range ss {
var addr *net.TCPAddr
addr, err = net.ResolveTCPAddr("tcp", s)
if err != nil {
return
}
ret = append(ret, torrent.Peer{
IP: addr.IP,
Port: addr.Port,
})
}
return
}
func bytesCompleted(tc *torrent.Client) (ret int64) {
for _, t := range tc.Torrents() {
if t.Info() != nil {
ret += t.BytesCompleted()
}
}
return
}
// Returns an estimate of the total bytes for all torrents.
func totalBytesEstimate(tc *torrent.Client) (ret int64) {
var noInfo, hadInfo int64
for _, t := range tc.Torrents() {
info := t.Info()
if info == nil {
noInfo++
continue
}
ret += info.TotalLength()
hadInfo++
}
if hadInfo != 0 {
// Treat each torrent without info as the average of those with,
// rounded up.
ret += (noInfo*ret + hadInfo - 1) / hadInfo
}
return
}
func progressLine(tc *torrent.Client) string {
return fmt.Sprintf("\033[K%s / %s\r", humanize.Bytes(uint64(bytesCompleted(tc))), humanize.Bytes(uint64(totalBytesEstimate(tc))))
}
func dstFileName(picked string) string {
parts := strings.Split(picked, "/")
return parts[len(parts)-1]
}
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
var rootGroup struct {
Client torrent.Config `group:"Client Options"`
TestPeers []string `long:"test-peer" description:"address of peer to inject to every torrent"`
Pick string `long:"pick" description:"filename to pick"`
}
// Don't pass flags.PrintError because it's inconsistent with printing.
// https://github.com/jessevdk/go-flags/issues/132
parser := flags.NewParser(&rootGroup, flags.HelpFlag|flags.PassDoubleDash)
parser.Usage = "[OPTIONS] (magnet URI or .torrent file path)..."
posArgs, err := parser.Parse()
if err != nil {
fmt.Fprintf(os.Stderr, "%s", "Download from the BitTorrent network.\n\n")
fmt.Println(err)
os.Exit(2)
}
log.Printf("File to pick: %s", rootGroup.Pick)
testPeers, err := resolvedPeerAddrs(rootGroup.TestPeers)
if err != nil {
log.Fatal(err)
}
if len(posArgs) == 0 {
fmt.Fprintln(os.Stderr, "no torrents specified")
return
}
tmpdir, err := ioutil.TempDir("", "torrent-pick-")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(tmpdir)
rootGroup.Client.DataDir = tmpdir
client, err := torrent.NewClient(&rootGroup.Client)
if err != nil {
log.Fatalf("error creating client: %s", err)
}
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
client.WriteStatus(w)
})
defer client.Close()
dstName := dstFileName(rootGroup.Pick)
f, err := os.Create(dstName)
if err != nil {
log.Fatal(err)
}
dstWriter := bufio.NewWriter(f)
done := make(chan struct{})
for _, arg := range posArgs {
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
}
}()
t.AddPeers(testPeers)
go func() {
defer close(done)
<-t.GotInfo()
for _, file := range t.Files() {
if file.DisplayPath() != rootGroup.Pick {
continue
}
srcReader := missinggo.NewSectionReadSeeker(t.NewReader(), file.Offset(), file.Length())
io.Copy(dstWriter, srcReader)
return
}
log.Print("file not found")
}()
}
ticker := time.NewTicker(time.Second)
waitDone:
for {
select {
case <-done:
break waitDone
case <-ticker.C:
os.Stdout.WriteString(progressLine(client))
}
}
if rootGroup.Client.Seed {
select {}
}
}