10 "github.com/anacrolix/torrent/bencode"
13 // Also known as a torrent file.
14 type MetaInfo struct {
15 InfoBytes bencode.Bytes `bencode:"info,omitempty"` // BEP 3
16 Announce string `bencode:"announce,omitempty"` // BEP 3
17 AnnounceList AnnounceList `bencode:"announce-list,omitempty"` // BEP 12
18 Nodes []Node `bencode:"nodes,omitempty,ignore_unmarshal_type_error"` // BEP 5
19 // Where's this specified? Mentioned at
20 // https://wiki.theory.org/index.php/BitTorrentSpecification: (optional) the creation time of
21 // the torrent, in standard UNIX epoch format (integer, seconds since 1-Jan-1970 00:00:00 UTC)
22 CreationDate int64 `bencode:"creation date,omitempty,ignore_unmarshal_type_error"`
23 Comment string `bencode:"comment,omitempty"`
24 CreatedBy string `bencode:"created by,omitempty"`
25 Encoding string `bencode:"encoding,omitempty"`
26 UrlList UrlList `bencode:"url-list,omitempty"` // BEP 19 WebSeeds
27 // BEP 52 (BitTorrent v2): Keys are file merkle roots ("pieces root"s), and the values are the
28 // concatenated hashes of the merkle tree layer that corresponds to the piece length.
29 PieceLayers map[string]string `bencode:"piece layers,omitempty"`
32 // Load a MetaInfo from an io.Reader. Returns a non-nil error in case of failure.
33 func Load(r io.Reader) (*MetaInfo, error) {
35 d := bencode.NewDecoder(r)
43 // Convenience function for loading a MetaInfo from a file.
44 func LoadFromFile(filename string) (*MetaInfo, error) {
45 f, err := os.Open(filename)
55 func (mi MetaInfo) UnmarshalInfo() (info Info, err error) {
56 err = bencode.Unmarshal(mi.InfoBytes, &info)
60 func (mi *MetaInfo) HashInfoBytes() (infoHash Hash) {
61 return HashBytes(mi.InfoBytes)
64 // Encode to bencoded form.
65 func (mi MetaInfo) Write(w io.Writer) error {
66 return bencode.NewEncoder(w).Encode(mi)
69 // Set good default values in preparation for creating a new MetaInfo file.
70 func (mi *MetaInfo) SetDefaults() {
71 mi.CreatedBy = "github.com/anacrolix/torrent"
72 mi.CreationDate = time.Now().Unix()
75 // Creates a Magnet from a MetaInfo. Optional infohash and parsed info can be provided.
76 func (mi MetaInfo) Magnet(infoHash *Hash, info *Info) (m Magnet) {
77 m.Trackers = append(m.Trackers, mi.UpvertedAnnounceList().DistinctValues()...)
79 m.DisplayName = info.BestName()
82 m.InfoHash = *infoHash
84 m.InfoHash = mi.HashInfoBytes()
86 m.Params = make(url.Values)
87 m.Params["ws"] = mi.UrlList
91 // Returns the announce-list converted from the old single announce field if necessary.
92 func (mi *MetaInfo) UpvertedAnnounceList() AnnounceList {
93 if mi.AnnounceList.OverridesAnnounce(mi.Announce) {
94 return mi.AnnounceList
96 if mi.Announce != "" {
97 return [][]string{{mi.Announce}}