]> Sergey Matveev's repositories - btrtrc.git/blob - metainfo/info.go
Expose metainfo.GeneratePieces
[btrtrc.git] / metainfo / info.go
1 package metainfo
2
3 import (
4         "errors"
5         "fmt"
6         "io"
7         "os"
8         "path/filepath"
9         "strings"
10
11         "github.com/anacrolix/missinggo/slices"
12 )
13
14 // The info dictionary.
15 type Info struct {
16         PieceLength int64  `bencode:"piece length"`      // BEP3
17         Pieces      []byte `bencode:"pieces"`            // BEP3
18         Name        string `bencode:"name"`              // BEP3
19         Length      int64  `bencode:"length,omitempty"`  // BEP3, mutually exclusive with Files
20         Private     *bool  `bencode:"private,omitempty"` // BEP27
21         // TODO: Document this field.
22         Source string     `bencode:"source,omitempty"`
23         Files  []FileInfo `bencode:"files,omitempty"` // BEP3, mutually exclusive with Length
24 }
25
26 // This is a helper that sets Files and Pieces from a root path and its
27 // children.
28 func (info *Info) BuildFromFilePath(root string) (err error) {
29         info.Name = filepath.Base(root)
30         info.Files = nil
31         err = filepath.Walk(root, func(path string, fi os.FileInfo, err error) error {
32                 if err != nil {
33                         return err
34                 }
35                 if fi.IsDir() {
36                         // Directories are implicit in torrent files.
37                         return nil
38                 } else if path == root {
39                         // The root is a file.
40                         info.Length = fi.Size()
41                         return nil
42                 }
43                 relPath, err := filepath.Rel(root, path)
44                 if err != nil {
45                         return fmt.Errorf("error getting relative path: %s", err)
46                 }
47                 info.Files = append(info.Files, FileInfo{
48                         Path:   strings.Split(relPath, string(filepath.Separator)),
49                         Length: fi.Size(),
50                 })
51                 return nil
52         })
53         if err != nil {
54                 return
55         }
56         slices.Sort(info.Files, func(l, r FileInfo) bool {
57                 return strings.Join(l.Path, "/") < strings.Join(r.Path, "/")
58         })
59         err = info.GeneratePieces(func(fi FileInfo) (io.ReadCloser, error) {
60                 return os.Open(filepath.Join(root, strings.Join(fi.Path, string(filepath.Separator))))
61         })
62         if err != nil {
63                 err = fmt.Errorf("error generating pieces: %s", err)
64         }
65         return
66 }
67
68 // Concatenates all the files in the torrent into w. open is a function that
69 // gets at the contents of the given file.
70 func (info *Info) writeFiles(w io.Writer, open func(fi FileInfo) (io.ReadCloser, error)) error {
71         for _, fi := range info.UpvertedFiles() {
72                 r, err := open(fi)
73                 if err != nil {
74                         return fmt.Errorf("error opening %v: %s", fi, err)
75                 }
76                 wn, err := io.CopyN(w, r, fi.Length)
77                 r.Close()
78                 if wn != fi.Length {
79                         return fmt.Errorf("error copying %v: %s", fi, err)
80                 }
81         }
82         return nil
83 }
84
85 // Sets Pieces (the block of piece hashes in the Info) by using the passed
86 // function to get at the torrent data.
87 func (info *Info) GeneratePieces(open func(fi FileInfo) (io.ReadCloser, error)) (err error) {
88         if info.PieceLength == 0 {
89                 return errors.New("piece length must be non-zero")
90         }
91         pr, pw := io.Pipe()
92         go func() {
93                 err := info.writeFiles(pw, open)
94                 pw.CloseWithError(err)
95         }()
96         defer pr.Close()
97         info.Pieces, err = GeneratePieces(pr, info.PieceLength, nil)
98         return
99 }
100
101 func (info *Info) TotalLength() (ret int64) {
102         if info.IsDir() {
103                 for _, fi := range info.Files {
104                         ret += fi.Length
105                 }
106         } else {
107                 ret = info.Length
108         }
109         return
110 }
111
112 func (info *Info) NumPieces() int {
113         return len(info.Pieces) / 20
114 }
115
116 func (info *Info) IsDir() bool {
117         return len(info.Files) != 0
118 }
119
120 // The files field, converted up from the old single-file in the parent info
121 // dict if necessary. This is a helper to avoid having to conditionally handle
122 // single and multi-file torrent infos.
123 func (info *Info) UpvertedFiles() []FileInfo {
124         if len(info.Files) == 0 {
125                 return []FileInfo{{
126                         Length: info.Length,
127                         // Callers should determine that Info.Name is the basename, and
128                         // thus a regular file.
129                         Path: nil,
130                 }}
131         }
132         return info.Files
133 }
134
135 func (info *Info) Piece(index int) Piece {
136         return Piece{info, pieceIndex(index)}
137 }