]> Sergey Matveev's repositories - btrtrc.git/blob - file.go
Merge pull request #54 from zhulik/master
[btrtrc.git] / file.go
1 package torrent
2
3 import (
4         "strings"
5
6         "github.com/anacrolix/torrent/metainfo"
7 )
8
9 // Provides access to regions of torrent data that correspond to its files.
10 type File struct {
11         t      clientTorrent
12         path   string
13         offset int64
14         length int64
15         fi     metainfo.FileInfo
16 }
17
18 func (f *File) Torrent() Torrent {
19         return f.t
20 }
21
22 // Data for this file begins this far into the torrent.
23 func (f *File) Offset() int64 {
24         return f.offset
25 }
26
27 func (f File) FileInfo() metainfo.FileInfo {
28         return f.fi
29 }
30
31 func (f File) Path() string {
32         return f.path
33 }
34
35 func (f *File) Length() int64 {
36         return f.length
37 }
38
39 // The relative file path for a multi-file torrent, and the torrent name for a
40 // single-file torrent.
41 func (f *File) DisplayPath() string {
42         fip := f.FileInfo().Path
43         if len(fip) == 0 {
44                 return f.t.Info().Name
45         }
46         return strings.Join(fip, "/")
47
48 }
49
50 type FilePieceState struct {
51         Bytes int64 // Bytes within the piece that are part of this File.
52         PieceState
53 }
54
55 // Returns the state of pieces in this file.
56 func (f *File) State() (ret []FilePieceState) {
57         pieceSize := int64(f.t.usualPieceSize())
58         off := f.offset % pieceSize
59         remaining := f.length
60         for i := int(f.offset / pieceSize); ; i++ {
61                 if remaining == 0 {
62                         break
63                 }
64                 len1 := pieceSize - off
65                 if len1 > remaining {
66                         len1 = remaining
67                 }
68                 f.t.cl.mu.RLock()
69                 ps := f.t.pieceState(i)
70                 f.t.cl.mu.RUnlock()
71                 ret = append(ret, FilePieceState{len1, ps})
72                 off = 0
73                 remaining -= len1
74         }
75         return
76 }
77
78 // Marks pieces in the region of the file for download. This is a helper
79 // wrapping Torrent.SetRegionPriority.
80 func (f *File) PrioritizeRegion(off, len int64) {
81         if off < 0 || off >= f.length {
82                 return
83         }
84         if off+len > f.length {
85                 len = f.length - off
86         }
87         off += f.offset
88         f.t.SetRegionPriority(off, len)
89 }