]> Sergey Matveev's repositories - btrtrc.git/blob - t.go
Drop support for go 1.20
[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         err := t.cl.dropTorrent(t.infoHash, &wg)
104         if err != nil {
105                 panic(err)
106         }
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[PieceStateChange] {
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() (ret bool) {
128         t.cl.rLock()
129         ret = t.seeding()
130         t.cl.rUnlock()
131         return
132 }
133
134 // Clobbers the torrent display name if metainfo is unavailable.
135 // The display name is used as the torrent name while the metainfo is unavailable.
136 func (t *Torrent) SetDisplayName(dn string) {
137         t.nameMu.Lock()
138         if !t.haveInfo() {
139                 t.displayName = dn
140         }
141         t.nameMu.Unlock()
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.Value
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.rLock()
160         defer t.cl.rUnlock()
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, "Torrent.DownloadPieces")
192                 }
193         }
194 }
195
196 func (t *Torrent) CancelPieces(begin, end pieceIndex) {
197         t.cl.lock()
198         t.cancelPiecesLocked(begin, end, "Torrent.CancelPieces")
199         t.cl.unlock()
200 }
201
202 func (t *Torrent) cancelPiecesLocked(begin, end pieceIndex, reason string) {
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, reason)
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                 *t.files = append(*t.files, &File{
218                         t,
219                         strings.Join(append([]string{t.info.BestName()}, fi.BestPath()...), "/"),
220                         offset,
221                         fi.Length,
222                         fi,
223                         fi.DisplayPath(t.info),
224                         PiecePriorityNone,
225                 })
226                 offset += fi.Length
227         }
228 }
229
230 // Returns handles to the files in the torrent. This requires that the Info is
231 // available first.
232 func (t *Torrent) Files() []*File {
233         return *t.files
234 }
235
236 func (t *Torrent) AddPeers(pp []PeerInfo) (n int) {
237         t.cl.lock()
238         defer t.cl.unlock()
239         n = t.addPeers(pp)
240         return
241 }
242
243 // Marks the entire torrent for download. Requires the info first, see
244 // GotInfo. Sets piece priorities for historical reasons.
245 func (t *Torrent) DownloadAll() {
246         t.DownloadPieces(0, t.numPieces())
247 }
248
249 func (t *Torrent) String() string {
250         s := t.name()
251         if s == "" {
252                 return t.infoHash.HexString()
253         } else {
254                 return strconv.Quote(s)
255         }
256 }
257
258 func (t *Torrent) AddTrackers(announceList [][]string) {
259         t.cl.lock()
260         defer t.cl.unlock()
261         t.addTrackers(announceList)
262 }
263
264 func (t *Torrent) Piece(i pieceIndex) *Piece {
265         return t.piece(i)
266 }
267
268 func (t *Torrent) PeerConns() []*PeerConn {
269         t.cl.rLock()
270         defer t.cl.rUnlock()
271         ret := make([]*PeerConn, 0, len(t.conns))
272         for c := range t.conns {
273                 ret = append(ret, c)
274         }
275         return ret
276 }