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 Source string `bencode:"source,omitempty"`
23 Files []FileInfo `bencode:"files,omitempty"`
26 // This is a helper that sets Files and Pieces from a root path and its
28 func (info *Info) BuildFromFilePath(root string) (err error) {
29 info.Name = filepath.Base(root)
31 err = filepath.Walk(root, func(path string, fi os.FileInfo, err error) error {
36 // Directories are implicit in torrent files.
38 } else if path == root {
39 // The root is a file.
40 info.Length = fi.Size()
43 relPath, err := filepath.Rel(root, path)
45 return fmt.Errorf("error getting relative path: %s", err)
47 info.Files = append(info.Files, FileInfo{
48 Path: strings.Split(relPath, string(filepath.Separator)),
56 slices.Sort(info.Files, func(l, r FileInfo) bool {
57 return strings.Join(l.Path, "/") < strings.Join(r.Path, "/")
59 err = info.GeneratePieces(func(fi FileInfo) (io.ReadCloser, error) {
60 return os.Open(filepath.Join(root, strings.Join(fi.Path, string(filepath.Separator))))
63 err = fmt.Errorf("error generating pieces: %s", err)
68 func (info *Info) writeFiles(w io.Writer, open func(fi FileInfo) (io.ReadCloser, error)) error {
69 for _, fi := range info.UpvertedFiles() {
72 return fmt.Errorf("error opening %v: %s", fi, err)
74 wn, err := io.CopyN(w, r, fi.Length)
76 if wn != fi.Length || err != nil {
77 return fmt.Errorf("error hashing %v: %s", fi, err)
83 // Set info.Pieces by hashing info.Files.
84 func (info *Info) GeneratePieces(open func(fi FileInfo) (io.ReadCloser, error)) error {
85 if info.PieceLength == 0 {
86 return errors.New("piece length must be non-zero")
90 err := info.writeFiles(pw, open)
91 pw.CloseWithError(err)
97 wn, err := io.CopyN(hasher, pr, info.PieceLength)
107 pieces = hasher.Sum(pieces)
108 if wn < info.PieceLength {
116 func (info *Info) TotalLength() (ret int64) {
118 for _, fi := range info.Files {
127 func (info *Info) NumPieces() int {
128 if len(info.Pieces)%20 != 0 {
129 panic(len(info.Pieces))
131 return len(info.Pieces) / 20
134 func (info *Info) IsDir() bool {
135 return len(info.Files) != 0
138 // The files field, converted up from the old single-file in the parent info
139 // dict if necessary. This is a helper to avoid having to conditionally handle
140 // single and multi-file torrent infos.
141 func (info *Info) UpvertedFiles() []FileInfo {
142 if len(info.Files) == 0 {
145 // Callers should determine that Info.Name is the basename, and
146 // thus a regular file.
153 func (info *Info) Piece(index int) Piece {
154 return Piece{info, index}