forked from anacrolix/torrent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
59 lines (55 loc) · 1.33 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
// Converts magnet URIs and info hashes into torrent metainfo files.
package main
import (
"log"
"net/http"
"os"
"sync"
"github.com/anacrolix/tagflag"
"github.com/james-lawrence/torrent"
"github.com/james-lawrence/torrent/autobind"
"github.com/james-lawrence/torrent/bencode"
)
func main() {
args := struct {
tagflag.StartPos
Magnet []string
}{}
tagflag.Parse(&args)
cl, err := autobind.New().Bind(torrent.NewClient(nil))
if err != nil {
log.Fatalf("error creating client: %s", err)
}
http.HandleFunc("/torrent", func(w http.ResponseWriter, r *http.Request) {
cl.WriteStatus(w)
})
http.HandleFunc("/dht", func(w http.ResponseWriter, r *http.Request) {
for _, ds := range cl.DhtServers() {
ds.WriteStatus(w)
}
})
wg := sync.WaitGroup{}
for _, arg := range args.Magnet {
t, _, err := cl.MaybeStart(torrent.NewFromMagnet(arg))
if err != nil {
log.Fatalf("error adding magnet to client: %s", err)
}
wg.Add(1)
go func() {
defer wg.Done()
<-t.GotInfo()
mi := t.Metainfo()
cl.Stop(t.Metadata())
f, err := os.Create(t.Info().Name + ".torrent")
if err != nil {
log.Fatalf("error creating torrent metainfo file: %s", err)
}
defer f.Close()
err = bencode.NewEncoder(f).Encode(mi)
if err != nil {
log.Fatalf("error writing torrent metainfo file: %s", err)
}
}()
}
wg.Wait()
}