]> Sergey Matveev's repositories - btrtrc.git/blob - spec.go
cmd/torrentfs: Fix panic on missing info
[btrtrc.git] / spec.go
1 package torrent
2
3 import (
4         "fmt"
5
6         "github.com/anacrolix/torrent/metainfo"
7         "github.com/anacrolix/torrent/storage"
8 )
9
10 // Specifies a new torrent for adding to a client. There are helpers for magnet URIs and torrent
11 // metainfo files.
12 type TorrentSpec struct {
13         // The tiered tracker URIs.
14         Trackers  [][]string
15         InfoHash  metainfo.Hash
16         InfoBytes []byte
17         // The name to use if the Name field from the Info isn't available.
18         DisplayName string
19         Webseeds    []string
20         DhtNodes    []string
21         PeerAddrs   []string
22         // The combination of the "xs" and "as" fields in magnet links, for now.
23         Sources []string
24
25         // The chunk size to use for outbound requests. Defaults to 16KiB if not set.
26         ChunkSize int
27         Storage   storage.ClientImpl
28
29         // Whether to allow data download or upload
30         DisallowDataUpload   bool
31         DisallowDataDownload bool
32 }
33
34 func TorrentSpecFromMagnetUri(uri string) (spec *TorrentSpec, err error) {
35         m, err := metainfo.ParseMagnetUri(uri)
36         if err != nil {
37                 return
38         }
39         spec = &TorrentSpec{
40                 Trackers:    [][]string{m.Trackers},
41                 DisplayName: m.DisplayName,
42                 InfoHash:    m.InfoHash,
43                 Webseeds:    m.Params["ws"],
44                 Sources:     append(m.Params["xs"], m.Params["as"]...),
45                 PeerAddrs:   m.Params["x.pe"], // BEP 9
46                 // TODO: What's the parameter for DHT nodes?
47         }
48         return
49 }
50
51 func TorrentSpecFromMetaInfoErr(mi *metainfo.MetaInfo) (*TorrentSpec, error) {
52         info, err := mi.UnmarshalInfo()
53         if err != nil {
54                 return nil, fmt.Errorf("unmarshalling info: %w", err)
55         }
56         return &TorrentSpec{
57                 Trackers:    mi.UpvertedAnnounceList(),
58                 InfoHash:    mi.HashInfoBytes(),
59                 InfoBytes:   mi.InfoBytes,
60                 DisplayName: info.Name,
61                 Webseeds:    mi.UrlList,
62                 DhtNodes: func() (ret []string) {
63                         ret = make([]string, len(mi.Nodes))
64                         for _, node := range mi.Nodes {
65                                 ret = append(ret, string(node))
66                         }
67                         return
68                 }(),
69         }, nil
70 }
71
72 func TorrentSpecFromMetaInfo(mi *metainfo.MetaInfo) *TorrentSpec {
73         ts, err := TorrentSpecFromMetaInfoErr(mi)
74         if err != nil {
75                 panic(err)
76         }
77         return ts
78 }