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