-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
260 lines (211 loc) · 6.13 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
package main
import (
"flag"
"fmt"
"os"
"time"
"github.com/ritsource/torrent-client/output"
"github.com/ritsource/torrent-client/src"
)
var torrFn string
func init() {
// reading teh command-line flags
devflag := flag.Bool("dev", false, "to print developer logs or not") // to determine in dev-mode or not
flflag := flag.String("file", "", "path to the `.torrent` file") // `.torrent file path`
flag.Parse()
torrFn = *flflag
output.DevMode = *devflag
}
// variables to store data about download stats .
var (
TotalPieceCount int
DownloadedPieceCount int
TotalDataSize int
DownloadedDataSize int
DownloadStarted bool
)
func main() {
// if no `--file` value provided reading the `.torrent`
// file path as the 2nd command-line arguements
if torrFn == "" {
if len(os.Args) < 2 {
panic("no `.torrent` file provided")
}
torrFn = os.Args[1]
}
// print stats (different goroutine)
iv := true
go PrintStats(&iv)
// reading the `.torrent` file
err := src.ReadFile(torrFn)
if err != nil {
panic(fmt.Errorf("unable to read data from `.torrent` file, %v", err))
}
// set total piece count to what read on the `.torrent` file,
TotalPieceCount = len(src.Torr.Pieces)
ch1 := make(chan error) // holds tracker request error, when requested in a different goroutine
var peers []*src.Peer // holds pointers to `src.Peer` corresponding to each peer
// retrieving information about peers from tracker server
go func(prs *[]*src.Peer, c chan error) {
*prs, err = src.GetPeers()
c <- err
}(&peers, ch1)
// generating `src.Block` for each peers
for _, piece := range src.Torr.Pieces {
piece.GenBlocks()
}
// generating PFMap, mapping of piece and files, that determines
// in which file/files teh piece data needs to be written
src.Torr.GenPFMap()
// handling tracker request response (if error)
err = <-ch1
if err != nil {
panic(err)
}
// seeders holds the pointer to the peers from which data can be downloaded
seeders := AllSeeders{}
seeders.Find(peers)
// wait as long as there's no peeris ready/available to share files
for seeders.Len() < 1 {
time.Sleep(1 * time.Second)
}
// DownloadStarted indicates file download has started or not
DownloadStarted = true
// `AllSeeders.Download` efficiently downloads pieces
// of data from all the seeders concurrently
seeders.Download(src.Torr)
fmt.Println("\nDownload Complete!")
}
// PrintStats peints and updates stats about download process
// it requires a boolean as arguemnt for not so necessary reasons
func PrintStats(iv *bool) {
ticker := time.Tick(time.Second)
for {
<-ticker
perc := float64(DownloadedPieceCount) / float64(TotalPieceCount) * 100
var status string
if DownloadStarted {
status = "Downloading.."
} else {
status = "Getting info.."
}
if *iv == true {
*iv = false
status += "."
} else {
status += " "
*iv = true
}
fmt.Printf("\rDownloaded %.2f%%\tPieces %d/%d\t%v\t", float64(perc), DownloadedPieceCount, TotalPieceCount, status)
}
}
// AllSeeders is a slice of pointers to peers from which pieces
// of data can be downloaded (peers that has unchoked the client)
type AllSeeders []*src.Peer
// Len returns the length of `Seeders`
func (as *AllSeeders) Len() int {
return len(*as)
}
// Active checks and returns the number of
// seeders where peer connection is alive
func (as *AllSeeders) Active() int {
x := 0
for _, s := range *as {
if s.IsAlive() {
x++
}
}
return x
}
/*
Find is gonna disconnect with all the peers
and reestablish connection with all of them again
*/
func (as *AllSeeders) Find(peers []*src.Peer) {
for _, p := range peers {
go func(p *src.Peer) {
err := p.Ping()
if err == nil {
(*as) = append(*as, p)
}
}(p)
}
}
// Download downloads each of `src.Torr.Pieces` from the seeder
func (as *AllSeeders) Download(torr *src.Torrent) {
var done bool
go func(done *bool) {
for {
time.Sleep(1 * time.Second)
// if all the pieces are downloaded then break the loop
dn, comp := isDownComplete(torr.Pieces)
// print how many pieces has been downloaded yet, and reset `pidx = 0`
output.DevInfof("[%v] out of [%v] pieces has been downloaded", dn, len(torr.Pieces))
DownloadedPieceCount = dn
if comp == true {
output.DevInfof("all [%v] pieces has been downloaded **[DONE]**", dn)
*done = true
break
}
}
}(&done)
pidx := 0 // current piece index
sidx := 0 // current seeder/peer index
for !done {
time.Sleep(100 * time.Millisecond)
// when all the pieces are covered, reseting the `pidx = 0`
if pidx >= len(torr.Pieces) {
pidx = 0
}
// if all the seeder's are covered onc more time, reset `sidx = 0`
if sidx >= len(*as) {
sidx = 0
}
// pointer to the piece that has to be downloaded
piece := src.Torr.Pieces[pidx]
// if piece is currently downloading or has alreay been downloaded, then go to the next piece
if piece.Status == src.PieceStatusDownloaded || piece.Status == src.PieceStatusRequested {
pidx++
continue
}
// pointer to the peer
seeder := (*as)[sidx]
// if peer is available for download and has the piece, then request the piece from it
if seeder.IsFree() && seeder.HasPiece(pidx) {
output.DevInfof("requesting piece of index %v | to %v:%v\n", piece.Index, seeder.IP, seeder.Port)
// downloading teh piece in a different goroutine
go func(s *src.Peer, p *src.Piece) {
_, err := s.DownloadPiece(p)
switch err {
case nil:
// pass
case src.ErrPeerDisconnected:
go s.Ping()
default:
output.DevErrorf("%v\n", err)
}
}(seeder, piece)
// to go to the next-piece
pidx++
} else if !seeder.IsAlive() {
// if peer connection is closed, then reestablish the connection
go seeder.Ping()
}
// next-seeder
sidx++
}
}
// isDownComplete checks if all the pieces are downloaded
func isDownComplete(pieces []*src.Piece) (int, bool) {
boo := true // boo == true, all pieces are downloaded (none left)
dn := 0 // number of pieces to be downloaded
for _, p := range pieces {
if p.Status == src.PieceStatusDownloaded {
dn++
} else {
// if any piece is yet to be downloaded, set `boo = false`
boo = false
}
}
return dn, boo
}