12 "github.com/anacrolix/missinggo/slices"
15 // The info dictionary.
17 PieceLength int64 `bencode:"piece length"`
18 Pieces []byte `bencode:"pieces"`
19 Name string `bencode:"name"`
20 Length int64 `bencode:"length,omitempty"`
21 Private *bool `bencode:"private,omitempty"`
22 // TODO: Document this field.
23 Source string `bencode:"source,omitempty"`
24 Files []FileInfo `bencode:"files,omitempty"`
27 // This is a helper that sets Files and Pieces from a root path and its
29 func (info *Info) BuildFromFilePath(root string) (err error) {
30 info.Name = filepath.Base(root)
32 err = filepath.Walk(root, func(path string, fi os.FileInfo, err error) error {
37 // Directories are implicit in torrent files.
39 } else if path == root {
40 // The root is a file.
41 info.Length = fi.Size()
44 relPath, err := filepath.Rel(root, path)
46 return fmt.Errorf("error getting relative path: %s", err)
48 info.Files = append(info.Files, FileInfo{
49 Path: strings.Split(relPath, string(filepath.Separator)),
57 slices.Sort(info.Files, func(l, r FileInfo) bool {
58 return strings.Join(l.Path, "/") < strings.Join(r.Path, "/")
60 err = info.GeneratePieces(func(fi FileInfo) (io.ReadCloser, error) {
61 return os.Open(filepath.Join(root, strings.Join(fi.Path, string(filepath.Separator))))
64 err = fmt.Errorf("error generating pieces: %s", err)
69 // Concatenates all the files in the torrent into w. open is a function that
70 // gets at the contents of the given file.
71 func (info *Info) writeFiles(w io.Writer, open func(fi FileInfo) (io.ReadCloser, error)) error {
72 for _, fi := range info.UpvertedFiles() {
75 return fmt.Errorf("error opening %v: %s", fi, err)
77 wn, err := io.CopyN(w, r, fi.Length)
80 return fmt.Errorf("error copying %v: %s", fi, err)
86 // Sets Pieces (the block of piece hashes in the Info) by using the passed
87 // function to get at the torrent data.
88 func (info *Info) GeneratePieces(open func(fi FileInfo) (io.ReadCloser, error)) error {
89 if info.PieceLength == 0 {
90 return errors.New("piece length must be non-zero")
94 err := info.writeFiles(pw, open)
95 pw.CloseWithError(err)
101 wn, err := io.CopyN(hasher, pr, info.PieceLength)
111 pieces = hasher.Sum(pieces)
112 if wn < info.PieceLength {
120 func (info *Info) TotalLength() (ret int64) {
122 for _, fi := range info.Files {
131 func (info *Info) NumPieces() int {
132 return len(info.Pieces) / 20
135 func (info *Info) IsDir() bool {
136 return len(info.Files) != 0
139 // The files field, converted up from the old single-file in the parent info
140 // dict if necessary. This is a helper to avoid having to conditionally handle
141 // single and multi-file torrent infos.
142 func (info *Info) UpvertedFiles() []FileInfo {
143 if len(info.Files) == 0 {
146 // Callers should determine that Info.Name is the basename, and
147 // thus a regular file.
154 func (info *Info) Piece(index int) Piece {
155 return Piece{info, pieceIndex(index)}