]> Sergey Matveev's repositories - btrtrc.git/blob - t.go
Inlineable `(*Torrent).PieceState()` (#621)
[btrtrc.git] / t.go
1 package torrent
2
3 import (
4         "strconv"
5         "strings"
6
7         "github.com/anacrolix/missinggo/pubsub"
8         "github.com/anacrolix/sync"
9
10         "github.com/anacrolix/torrent/metainfo"
11 )
12
13 // The Torrent's infohash. This is fixed and cannot change. It uniquely identifies a torrent.
14 func (t *Torrent) InfoHash() metainfo.Hash {
15         return t.infoHash
16 }
17
18 // Returns a channel that is closed when the info (.Info()) for the torrent has become available.
19 func (t *Torrent) GotInfo() (ret <-chan struct{}) {
20         // TODO: We shouldn't need to lock to take a channel here, if the event is only ever set.
21         t.nameMu.RLock()
22         ret = t.gotMetainfoC
23         t.nameMu.RUnlock()
24         return
25 }
26
27 // Returns the metainfo info dictionary, or nil if it's not yet available.
28 func (t *Torrent) Info() (info *metainfo.Info) {
29         t.nameMu.RLock()
30         info = t.info
31         t.nameMu.RUnlock()
32         return
33 }
34
35 // Returns a Reader bound to the torrent's data. All read calls block until the data requested is
36 // actually available. Note that you probably want to ensure the Torrent Info is available first.
37 func (t *Torrent) NewReader() Reader {
38         return t.newReader(0, *t.length)
39 }
40
41 func (t *Torrent) newReader(offset, length int64) Reader {
42         r := reader{
43                 mu:     t.cl.locker(),
44                 t:      t,
45                 offset: offset,
46                 length: length,
47         }
48         r.readaheadFunc = r.defaultReadaheadFunc
49         t.addReader(&r)
50         return &r
51 }
52
53 type PieceStateRuns []PieceStateRun
54
55 func (me PieceStateRuns) String() (s string) {
56         if len(me) > 0 {
57                 var sb strings.Builder
58                 sb.WriteString(me[0].String())
59                 for i := 1; i < len(me); i += 1 {
60                         sb.WriteByte(' ')
61                         sb.WriteString(me[i].String())
62                 }
63                 return sb.String()
64         }
65         return
66 }
67
68 // Returns the state of pieces of the torrent. They are grouped into runs of same state. The sum of
69 // the state run-lengths is the number of pieces in the torrent.
70 func (t *Torrent) PieceStateRuns() (runs PieceStateRuns) {
71         t.cl.rLock()
72         runs = t.pieceStateRuns()
73         t.cl.rUnlock()
74         return
75 }
76
77 func (t *Torrent) PieceState(piece pieceIndex) (ps PieceState) {
78         t.cl.rLock()
79         ps = t.pieceState(piece)
80         t.cl.rUnlock()
81         return 
82 }
83
84 // The number of pieces in the torrent. This requires that the info has been
85 // obtained first.
86 func (t *Torrent) NumPieces() pieceIndex {
87         return t.numPieces()
88 }
89
90 // Get missing bytes count for specific piece.
91 func (t *Torrent) PieceBytesMissing(piece int) int64 {
92         t.cl.lock()
93         defer t.cl.unlock()
94
95         return int64(t.pieces[piece].bytesLeft())
96 }
97
98 // Drop the torrent from the client, and close it. It's always safe to do
99 // this. No data corruption can, or should occur to either the torrent's data,
100 // or connected peers.
101 func (t *Torrent) Drop() {
102         var wg sync.WaitGroup
103         defer wg.Wait()
104         t.cl.lock()
105         defer t.cl.unlock()
106         t.cl.dropTorrent(t.infoHash, &wg)
107 }
108
109 // Number of bytes of the entire torrent we have completed. This is the sum of
110 // completed pieces, and dirtied chunks of incomplete pieces. Do not use this
111 // for download rate, as it can go down when pieces are lost or fail checks.
112 // Sample Torrent.Stats.DataBytesRead for actual file data download rate.
113 func (t *Torrent) BytesCompleted() int64 {
114         t.cl.rLock()
115         defer t.cl.rUnlock()
116         return t.bytesCompleted()
117 }
118
119 // The subscription emits as (int) the index of pieces as their state changes.
120 // A state change is when the PieceState for a piece alters in value.
121 func (t *Torrent) SubscribePieceStateChanges() *pubsub.Subscription {
122         return t.pieceStateChanges.Subscribe()
123 }
124
125 // Returns true if the torrent is currently being seeded. This occurs when the
126 // client is willing to upload without wanting anything in return.
127 func (t *Torrent) Seeding() bool {
128         t.cl.lock()
129         defer t.cl.unlock()
130         return t.seeding()
131 }
132
133 // Clobbers the torrent display name. The display name is used as the torrent
134 // name if the metainfo is not available.
135 func (t *Torrent) SetDisplayName(dn string) {
136         t.nameMu.Lock()
137         defer t.nameMu.Unlock()
138         if t.haveInfo() {
139                 return
140         }
141         t.displayName = dn
142 }
143
144 // The current working name for the torrent. Either the name in the info dict,
145 // or a display name given such as by the dn value in a magnet link, or "".
146 func (t *Torrent) Name() string {
147         return t.name()
148 }
149
150 // The completed length of all the torrent data, in all its files. This is
151 // derived from the torrent info, when it is available.
152 func (t *Torrent) Length() int64 {
153         return *t.length
154 }
155
156 // Returns a run-time generated metainfo for the torrent that includes the
157 // info bytes and announce-list as currently known to the client.
158 func (t *Torrent) Metainfo() metainfo.MetaInfo {
159         t.cl.lock()
160         defer t.cl.unlock()
161         return t.newMetaInfo()
162 }
163
164 func (t *Torrent) addReader(r *reader) {
165         t.cl.lock()
166         defer t.cl.unlock()
167         if t.readers == nil {
168                 t.readers = make(map[*reader]struct{})
169         }
170         t.readers[r] = struct{}{}
171         r.posChanged()
172 }
173
174 func (t *Torrent) deleteReader(r *reader) {
175         delete(t.readers, r)
176         t.readersChanged()
177 }
178
179 // Raise the priorities of pieces in the range [begin, end) to at least Normal
180 // priority. Piece indexes are not the same as bytes. Requires that the info
181 // has been obtained, see Torrent.Info and Torrent.GotInfo.
182 func (t *Torrent) DownloadPieces(begin, end pieceIndex) {
183         t.cl.lock()
184         t.downloadPiecesLocked(begin, end)
185         t.cl.unlock()
186 }
187
188 func (t *Torrent) downloadPiecesLocked(begin, end pieceIndex) {
189         for i := begin; i < end; i++ {
190                 if t.pieces[i].priority.Raise(PiecePriorityNormal) {
191                         t.updatePiecePriority(i)
192                 }
193         }
194 }
195
196 func (t *Torrent) CancelPieces(begin, end pieceIndex) {
197         t.cl.lock()
198         t.cancelPiecesLocked(begin, end)
199         t.cl.unlock()
200 }
201
202 func (t *Torrent) cancelPiecesLocked(begin, end pieceIndex) {
203         for i := begin; i < end; i++ {
204                 p := &t.pieces[i]
205                 if p.priority == PiecePriorityNone {
206                         continue
207                 }
208                 p.priority = PiecePriorityNone
209                 t.updatePiecePriority(i)
210         }
211 }
212
213 func (t *Torrent) initFiles() {
214         var offset int64
215         t.files = new([]*File)
216         for _, fi := range t.info.UpvertedFiles() {
217                 var path []string
218                 if len(fi.PathUTF8) != 0 {
219                         path = fi.PathUTF8
220                 } else {
221                         path = fi.Path
222                 }
223                 dp := t.info.Name
224                 if len(fi.Path) != 0 {
225                         dp = strings.Join(fi.Path, "/")
226                 }
227                 *t.files = append(*t.files, &File{
228                         t,
229                         strings.Join(append([]string{t.info.Name}, path...), "/"),
230                         offset,
231                         fi.Length,
232                         fi,
233                         dp,
234                         PiecePriorityNone,
235                 })
236                 offset += fi.Length
237         }
238
239 }
240
241 // Returns handles to the files in the torrent. This requires that the Info is
242 // available first.
243 func (t *Torrent) Files() []*File {
244         return *t.files
245 }
246
247 func (t *Torrent) AddPeers(pp []PeerInfo) (n int) {
248         t.cl.lock()
249         n = t.addPeers(pp)
250         t.cl.unlock()
251         return
252 }
253
254 // Marks the entire torrent for download. Requires the info first, see
255 // GotInfo. Sets piece priorities for historical reasons.
256 func (t *Torrent) DownloadAll() {
257         t.DownloadPieces(0, t.numPieces())
258 }
259
260 func (t *Torrent) String() string {
261         s := t.name()
262         if s == "" {
263                 return t.infoHash.HexString()
264         } else {
265                 return strconv.Quote(s)
266         }
267 }
268
269 func (t *Torrent) AddTrackers(announceList [][]string) {
270         t.cl.lock()
271         defer t.cl.unlock()
272         t.addTrackers(announceList)
273 }
274
275 func (t *Torrent) Piece(i pieceIndex) *Piece {
276         return t.piece(i)
277 }
278
279 func (t *Torrent) PeerConns() []*PeerConn {
280         t.cl.rLock()
281         defer t.cl.rUnlock()
282         ret := make([]*PeerConn, 0, len(t.conns))
283         for c := range t.conns {
284                 ret = append(ret, c)
285         }
286         return ret
287 }