FedP2P/cmd/magnet-metainfo/main.go

60 lines
1.2 KiB
Go
Raw Normal View History

// Converts magnet URIs and info hashes into torrent metainfo files.
package main
import (
"log"
"net/http"
"os"
"sync"
_ "github.com/anacrolix/envpprof"
2017-08-27 09:46:06 +08:00
"github.com/anacrolix/tagflag"
2019-08-21 18:58:40 +08:00
"github.com/anacrolix/torrent"
2015-04-28 13:24:17 +08:00
"github.com/anacrolix/torrent/bencode"
)
func main() {
2017-08-27 09:46:06 +08:00
args := struct {
tagflag.StartPos
Magnet []string
}{}
tagflag.Parse(&args)
cl, err := 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{}
2017-08-27 09:46:06 +08:00
for _, arg := range args.Magnet {
t, err := cl.AddMagnet(arg)
if err != nil {
log.Fatalf("error adding magnet to client: %s", err)
}
wg.Add(1)
go func() {
defer wg.Done()
<-t.GotInfo()
2016-04-03 16:40:43 +08:00
mi := t.Metainfo()
t.Drop()
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()
}