]> Sergey Matveev's repositories - btrtrc.git/blob - metainfo/metainfo.go
Need to break from the parent soon...
[btrtrc.git] / metainfo / metainfo.go
1 package metainfo
2
3 import (
4         "crypto/sha1"
5         "github.com/anacrolix/libtorgo/bencode"
6         "io"
7         "os"
8 )
9
10 // Information specific to a single file inside the MetaInfo structure.
11 type FileInfo struct {
12         Length int64    `bencode:"length"`
13         Path   []string `bencode:"path"`
14 }
15
16 // Load a MetaInfo from an io.Reader. Returns a non-nil error in case of
17 // failure.
18 func Load(r io.Reader) (*MetaInfo, error) {
19         var mi MetaInfo
20         d := bencode.NewDecoder(r)
21         err := d.Decode(&mi)
22         if err != nil {
23                 return nil, err
24         }
25         return &mi, nil
26 }
27
28 // Convenience function for loading a MetaInfo from a file.
29 func LoadFromFile(filename string) (*MetaInfo, error) {
30         f, err := os.Open(filename)
31         if err != nil {
32                 return nil, err
33         }
34         defer f.Close()
35         return Load(f)
36 }
37
38 // The info dictionary.
39 type Info struct {
40         PieceLength int64      `bencode:"piece length"`
41         Pieces      []byte     `bencode:"pieces"`
42         Name        string     `bencode:"name"`
43         Length      int64      `bencode:"length,omitempty"`
44         Private     bool       `bencode:"private,omitempty"`
45         Files       []FileInfo `bencode:"files,omitempty"`
46 }
47
48 // The info dictionary with its hash and raw bytes exposed, as these are
49 // important to Bittorrent.
50 type InfoEx struct {
51         Info
52         Hash  []byte
53         Bytes []byte
54 }
55
56 func (this *InfoEx) UnmarshalBencode(data []byte) error {
57         this.Bytes = make([]byte, 0, len(data))
58         this.Bytes = append(this.Bytes, data...)
59         h := sha1.New()
60         h.Write(this.Bytes)
61         this.Hash = h.Sum(this.Hash)
62         return bencode.Unmarshal(data, &this.Info)
63 }
64
65 func (this *InfoEx) MarshalBencode() ([]byte, error) {
66         return bencode.Marshal(&this.Info)
67 }
68
69 type MetaInfo struct {
70         Info         InfoEx      `bencode:"info"`
71         Announce     string      `bencode:"announce"`
72         AnnounceList [][]string  `bencode:"announce-list,omitempty"`
73         CreationDate int64       `bencode:"creation date,omitempty"`
74         Comment      string      `bencode:"comment,omitempty"`
75         CreatedBy    string      `bencode:"created by,omitempty"`
76         Encoding     string      `bencode:"encoding,omitempty"`
77         URLList      interface{} `bencode:"url-list,omitempty"`
78 }