FedP2P/cmd/torrent/serve.go

84 lines
2.3 KiB
Go
Raw Normal View History

2021-11-04 17:02:55 +08:00
package main
import (
"fmt"
"net/http"
"path/filepath"
2022-06-20 16:40:53 +08:00
"github.com/anacrolix/bargle"
2021-11-04 17:02:55 +08:00
"github.com/anacrolix/log"
"github.com/anacrolix/torrent"
"github.com/anacrolix/torrent/bencode"
"github.com/anacrolix/torrent/metainfo"
"github.com/anacrolix/torrent/storage"
)
2022-06-20 16:40:53 +08:00
func serve() (cmd bargle.Command) {
filePath := &bargle.Positional[string]{}
cmd.Positionals = append(cmd.Positionals, filePath)
cmd.DefaultAction = func() error {
2021-11-04 17:02:55 +08:00
cfg := torrent.NewDefaultClientConfig()
cfg.Seed = true
cl, err := torrent.NewClient(cfg)
if err != nil {
return fmt.Errorf("new torrent client: %w", err)
}
defer cl.Close()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
cl.WriteStatus(w)
})
2022-06-23 20:44:06 +08:00
totalLength, err := totalLength(filePath)
if err != nil {
return fmt.Errorf("calculating total length of %q: %v", filePath, err)
}
pieceLength := metainfo.ChoosePieceLength(totalLength)
2021-11-04 17:02:55 +08:00
info := metainfo.Info{
2022-06-23 20:44:06 +08:00
PieceLength: pieceLength,
2021-11-04 17:02:55 +08:00
}
2022-06-20 16:40:53 +08:00
err = info.BuildFromFilePath(filePath.Value)
2021-11-04 17:02:55 +08:00
if err != nil {
2022-06-20 16:40:53 +08:00
return fmt.Errorf("building info from path %q: %w", filePath.Value, err)
2021-11-04 17:02:55 +08:00
}
for _, fi := range info.Files {
log.Printf("added %q", fi.Path)
}
mi := metainfo.MetaInfo{
InfoBytes: bencode.MustMarshal(info),
}
pc, err := storage.NewDefaultPieceCompletionForDir(".")
if err != nil {
return fmt.Errorf("new piece completion: %w", err)
}
defer pc.Close()
ih := mi.HashInfoBytes()
to, _ := cl.AddTorrentOpt(torrent.AddTorrentOpts{
InfoHash: ih,
Storage: storage.NewFileOpts(storage.NewFileClientOpts{
2022-06-20 16:40:53 +08:00
ClientBaseDir: filePath.Value,
2021-11-04 17:02:55 +08:00
FilePathMaker: func(opts storage.FilePathMakerOpts) string {
return filepath.Join(opts.File.Path...)
},
TorrentDirMaker: nil,
PieceCompletion: pc,
}),
})
defer to.Drop()
err = to.MergeSpec(&torrent.TorrentSpec{
InfoBytes: mi.InfoBytes,
Trackers: [][]string{{
`wss://tracker.btorrent.xyz`,
`wss://tracker.openwebtorrent.com`,
"http://p4p.arenabg.com:1337/announce",
"udp://tracker.opentrackr.org:1337/announce",
"udp://tracker.openbittorrent.com:6969/announce",
}},
2021-11-04 17:02:55 +08:00
})
if err != nil {
return fmt.Errorf("setting trackers: %w", err)
}
2022-06-14 16:23:00 +08:00
fmt.Printf("%v: %v\n", to, to.Metainfo().Magnet(&ih, &info))
2021-11-04 17:02:55 +08:00
select {}
2022-06-20 16:40:53 +08:00
}
return
2021-11-04 17:02:55 +08:00
}