-
Notifications
You must be signed in to change notification settings - Fork 0
/
richkago.go
316 lines (280 loc) · 6.31 KB
/
richkago.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package richkago
import (
"errors"
"fmt"
"golang.org/x/sync/errgroup"
"io"
"net/http"
"os"
"strconv"
"time"
)
const (
version = "Alpha/0.0.1"
userAgent = "Richkago" + version
coroutineLimit = 10
sliceThreshold = 10 * 1024 * 1024 // 10 MiB
timeout = 3 * time.Second
retryTimes = 5
chunkSize = 102400
)
// readWithTimeout read data from source with timeout limit
func readWithTimeout(reader io.Reader, buffer []byte, controller *Controller, file *os.File, downloaded *int64, chunkID string) error {
// Make a error chan
ch := make(chan error, 1)
go func() {
// Read data
n, err := reader.Read(buffer)
if n > 0 {
// Write to file
_, err = file.Write(buffer[:n])
if err != nil {
ch <- err
return
}
// Calc amount of downloaded data
*downloaded += int64(n)
}
ch <- err
}()
// Error and timeout handler
select {
case err := <-ch:
// Update amount of downloaded data
if controller != nil {
controller.UpdateProgress(*downloaded, chunkID)
}
return err
case <-time.After(timeout):
return errors.New("timeout while reading data")
}
}
// downloadRange download a file with many slices
func downloadRange(client *http.Client, url string, start, end int64, destination string, controller *Controller) error {
// Build request header
headers := map[string]string{
"User-Agent": userAgent,
"Range": fmt.Sprintf("bytes=%d-%d", start, end),
}
retries := retryTimes
var err error
for retries > 0 {
// Get header info
var req *http.Request
req, err = http.NewRequest("GET", url, nil)
if err != nil {
retries--
time.Sleep(1 * time.Second)
continue
}
for k, v := range headers {
req.Header.Add(k, v)
}
// Read http header
var resp *http.Response
resp, err = client.Do(req)
if err != nil || resp.StatusCode != http.StatusPartialContent {
retries--
time.Sleep(1 * time.Second)
continue
}
defer func(Body io.ReadCloser) {
err = Body.Close()
if err != nil {
panic(err)
}
}(resp.Body)
// Pre-create file
file, _ := os.OpenFile(destination, os.O_WRONLY, 0644)
defer func(file *os.File) {
err = file.Close()
if err != nil {
panic(err)
}
}(file)
_, err = file.Seek(start, io.SeekStart)
if err != nil {
retries--
time.Sleep(1 * time.Second)
continue
}
// Create goroutines to download
buffer := make([]byte, chunkSize)
var downloaded int64
for {
// Controller pin
if controller.paused {
time.Sleep(1 * time.Second)
continue
}
// Start read stream
err = readWithTimeout(resp.Body, buffer, controller, file, &downloaded, fmt.Sprintf("%d-%d", start, end))
if err == io.EOF {
break
} else if err != nil {
break
}
}
// Error handler
if err != nil && err != io.EOF {
retries--
time.Sleep(1 * time.Second)
continue
}
return nil
}
return err
}
// downloadSingle download a file directly
func downloadSingle(client *http.Client, url, destination string, controller *Controller) error {
// Build request header
headers := map[string]string{
"User-Agent": userAgent,
}
retries := retryTimes
for retries > 0 {
// Get header info
req, _ := http.NewRequest("GET", url, nil)
for k, v := range headers {
req.Header.Add(k, v)
}
// Read http header
resp, err := client.Do(req)
if err != nil || resp.StatusCode != http.StatusOK {
retries--
time.Sleep(1 * time.Second)
continue
}
defer func(Body io.ReadCloser) {
err = Body.Close()
if err != nil {
panic(err)
}
}(resp.Body)
// Pre-create file
file, _ := os.OpenFile(destination, os.O_WRONLY, 0644)
defer func(file *os.File) {
err = file.Close()
if err != nil {
panic(err)
}
}(file)
// Start downloading
buffer := make([]byte, chunkSize)
var downloaded int64
for {
// Controller pin
if controller.paused {
time.Sleep(1 * time.Second)
continue
}
// Start read stream
var n int
n, err = resp.Body.Read(buffer)
if err != nil {
break
}
if n > 0 {
_, err = file.Write(buffer[:n])
if err != nil {
return err
}
downloaded += int64(n)
controller.UpdateProgress(downloaded, "")
}
}
// Error handler
if err != nil {
retries--
time.Sleep(1 * time.Second)
continue
} else {
return err
}
}
return nil
}
// Download main download task creator
func Download(url, destination string, controller *Controller) (float64, int64, error) {
// Create http client
client := &http.Client{}
// Get header info
req, err := http.NewRequest("HEAD", url, nil)
if err != nil {
controller.excepted = true
return 0, 0, err
}
req.Header.Add("User-Agent", userAgent)
// Read http header
resp, err := client.Do(req)
if err != nil {
controller.excepted = true
return 0, 0, err
}
defer func(Body io.ReadCloser) {
err = Body.Close()
if err != nil {
panic(err)
}
}(resp.Body)
sizeStr := resp.Header.Get("Content-Length")
fileSize, _ := strconv.ParseInt(sizeStr, 10, 64)
controller.totalSize = fileSize
// Calc slices size
if fileSize <= sliceThreshold {
file, _ := os.Create(destination)
err = file.Truncate(fileSize)
if err != nil {
controller.excepted = true
return 0, 0, err
}
err = file.Close()
if err != nil {
controller.excepted = true
return 0, 0, err
}
// Too small
startTime := time.Now()
err = downloadSingle(client, url, destination, controller)
if err != nil {
controller.excepted = true
return 0, 0, err
}
endTime := time.Now()
return endTime.Sub(startTime).Seconds(), fileSize, nil
}
// Pre-create file
partSize := fileSize / coroutineLimit
file, _ := os.Create(destination)
err = file.Truncate(fileSize)
if err != nil {
controller.excepted = true
return 0, 0, err
}
err = file.Close()
if err != nil {
controller.excepted = true
return 0, 0, err
}
// Start download goroutines
group := new(errgroup.Group)
for i := 0; i < coroutineLimit; i++ {
start := int64(i) * partSize
end := start + partSize - 1
if i == coroutineLimit-1 {
end = fileSize - 1
}
group.Go(func() error {
err = downloadRange(client, url, start, end, destination, controller)
return err
})
}
// Start all tasks
startTime := time.Now()
if err = group.Wait(); err != nil {
controller.excepted = true
return 0, 0, err
}
endTime := time.Now()
return endTime.Sub(startTime).Seconds(), fileSize, nil
}