8 "github.com/anacrolix/args"
9 "github.com/anacrolix/log"
10 "github.com/anacrolix/torrent"
11 "github.com/anacrolix/torrent/bencode"
12 "github.com/anacrolix/torrent/metainfo"
13 "github.com/anacrolix/torrent/storage"
16 func serve(ctx args.SubCmdCtx) error {
18 ctx.Parse(args.Pos("filePath", &filePath))
19 ctx.Defer(func() error {
20 cfg := torrent.NewDefaultClientConfig()
22 cl, err := torrent.NewClient(cfg)
24 return fmt.Errorf("new torrent client: %w", err)
27 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
30 totalLength, err := totalLength(filePath)
32 return fmt.Errorf("calculating total length of %q: %v", filePath, err)
34 pieceLength := choosePieceLength(totalLength)
35 info := metainfo.Info{
36 PieceLength: pieceLength,
38 err = info.BuildFromFilePath(filePath)
40 return fmt.Errorf("building info from path %q: %w", filePath, err)
42 for _, fi := range info.Files {
43 log.Printf("added %q", fi.Path)
45 mi := metainfo.MetaInfo{
46 InfoBytes: bencode.MustMarshal(info),
48 pc, err := storage.NewDefaultPieceCompletionForDir(".")
50 return fmt.Errorf("new piece completion: %w", err)
53 ih := mi.HashInfoBytes()
54 to, _ := cl.AddTorrentOpt(torrent.AddTorrentOpts{
56 Storage: storage.NewFileOpts(storage.NewFileClientOpts{
57 ClientBaseDir: filePath,
58 FilePathMaker: func(opts storage.FilePathMakerOpts) string {
59 return filepath.Join(opts.File.Path...)
66 err = to.MergeSpec(&torrent.TorrentSpec{
67 InfoBytes: mi.InfoBytes,
68 Trackers: [][]string{{
69 `wss://tracker.btorrent.xyz`,
70 `wss://tracker.openwebtorrent.com`,
71 "http://p4p.arenabg.com:1337/announce",
72 "udp://tracker.opentrackr.org:1337/announce",
73 "udp://tracker.openbittorrent.com:6969/announce",
77 return fmt.Errorf("setting trackers: %w", err)
79 fmt.Printf("%v: %v\n", to, to.Metainfo().Magnet(&ih, &info))