forked from itchio/butler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dl.go
139 lines (116 loc) · 3.46 KB
/
dl.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
package main
import (
"fmt"
"io"
"math"
"net/http"
"os"
"github.com/dustin/go-humanize"
"github.com/go-errors/errors"
"github.com/itchio/butler/comm"
"github.com/itchio/httpkit/timeout"
"github.com/itchio/wharf/counter"
)
const bufferSize = 128 * 1024
func dl(url string, dest string) {
_, err := tryDl(url, dest)
if err != nil {
comm.Die(err.Error())
}
}
func tryDl(url string, dest string) (int64, error) {
existingBytes := int64(0)
stats, err := os.Lstat(dest)
if err == nil {
existingBytes = stats.Size()
}
client := timeout.NewDefaultClient()
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("User-Agent", userAgent())
byteRange := fmt.Sprintf("bytes=%d-", existingBytes)
req.Header.Set("Range", byteRange)
resp, err := client.Do(req)
if err != nil {
return 0, errors.Wrap(err, 1)
}
defer resp.Body.Close()
doDownload := true
totalBytes := existingBytes + resp.ContentLength
hostInfo := fmt.Sprintf("%s at %s", resp.Header.Get("Server"), req.Host)
switch resp.StatusCode {
case 200: // OK
comm.Debugf("HTTP 200 OK (no byte range support)")
totalBytes = resp.ContentLength
if existingBytes == resp.ContentLength {
// already have the exact same number of bytes, hopefully the same ones
doDownload = false
} else {
// will send data, but doesn't support byte ranges
existingBytes = 0
os.Truncate(dest, 0)
}
case 206: // Partial Content
comm.Debugf("HTTP 206 Partial Content")
// will send incremental data
case 416: // Requested Range not Satisfiable
comm.Debugf("HTTP 416 Requested Range not Satisfiable")
// already has everything
doDownload = false
req, _ := http.NewRequest("HEAD", url, nil)
req.Header.Set("User-Agent", userAgent())
resp, err = client.Do(req)
if err != nil {
return 0, errors.Wrap(err, 1)
}
if existingBytes > resp.ContentLength {
comm.Debugf("Existing file too big (%d), truncating to %d", existingBytes, resp.ContentLength)
existingBytes = resp.ContentLength
os.Truncate(dest, existingBytes)
}
totalBytes = existingBytes
default:
return 0, fmt.Errorf("%s responded with HTTP %s", hostInfo, resp.Status)
}
if doDownload {
if existingBytes > 0 {
comm.Logf("Resuming (%s + %s = %s) download from %s", humanize.IBytes(uint64(existingBytes)), humanize.IBytes(uint64(resp.ContentLength)), humanize.IBytes(uint64(totalBytes)), hostInfo)
} else {
comm.Logf("Downloading %s from %s", humanize.IBytes(uint64(resp.ContentLength)), hostInfo)
}
err = appendAllToFile(resp.Body, dest, existingBytes, totalBytes)
if err != nil {
return 0, errors.Wrap(err, 1)
}
} else {
comm.Log("Already fully downloaded")
}
_, err = checkIntegrity(resp, totalBytes, dest)
if err != nil {
comm.Log("Integrity checks failed, truncating")
os.Truncate(dest, 0)
return 0, errors.Wrap(err, 1)
}
return totalBytes, nil
}
func appendAllToFile(src io.Reader, dest string, existingBytes int64, totalBytes int64) error {
out, _ := os.OpenFile(dest, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
defer out.Close()
prevPercent := 0.0
comm.StartProgress()
onWrite := func(bytesDownloaded int64) {
bytesWritten := existingBytes + bytesDownloaded
percent := float64(bytesWritten) / float64(totalBytes)
if math.Abs(percent-prevPercent) < 0.0001 {
return
}
prevPercent = percent
comm.Progress(percent)
}
counter := counter.NewWriterCallback(onWrite, out)
_, err := io.Copy(counter, src)
if err != nil {
return errors.Wrap(err, 1)
}
comm.EndProgress()
return nil
}