-
Notifications
You must be signed in to change notification settings - Fork 30
/
index.js
230 lines (198 loc) · 6.29 KB
/
index.js
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
var request = require('request')
var fs = require('fs')
var path = require('path')
var log = require('single-line-log').stdout
var progress = require('progress-stream')
var prettyBytes = require('pretty-bytes')
var throttle = require('throttleit')
var EventEmitter = require('events').EventEmitter
var debug = require('debug')('nugget')
function noop () {}
module.exports = function (urls, opts, cb) {
if (!Array.isArray(urls)) urls = [urls]
if (urls.length === 1) opts.singleTarget = true
var defaultProps = {}
if (opts.sockets) {
var sockets = +opts.sockets
defaultProps.pool = {maxSockets: sockets}
}
if (opts.proxy) {
defaultProps.proxy = opts.proxy
}
if (opts.strictSSL !== null) {
defaultProps.strictSSL = opts.strictSSL
}
if (Object.keys(defaultProps).length > 0) {
request = request.defaults(defaultProps)
}
var downloads = []
var errors = []
var pending = 0
var truncated = urls.length * 2 >= (process.stdout.rows - 15)
urls.forEach(function (url) {
debug('start dl', url)
pending++
var dl = startDownload(url, opts, function done (err) {
debug('done dl', url, pending)
if (err) {
debug('error dl', url, err)
errors.push(err)
dl.error = err.message
}
if (truncated) {
var i = downloads.indexOf(dl)
downloads.splice(i, 1)
downloads.push(dl)
}
if (--pending === 0) {
render()
cb(errors.length ? errors : undefined)
}
})
downloads.push(dl)
dl.on('start', function (progressStream) {
throttledRender()
})
dl.on('progress', function (data) {
debug('progress', url, data.percentage)
dl.speed = data.speed
if (dl.percentage === 100) render()
else throttledRender()
})
})
var _log = opts.quiet ? noop : log
render()
var throttledRender = throttle(render, opts.frequency || 250)
if (opts.singleTarget) return downloads[0]
else return downloads
function render () {
var height = process.stdout.rows
var rendered = 0
var output = ''
var totalSpeed = 0
downloads.forEach(function (dl) {
if (2 * rendered >= height - 15) return
rendered++
if (dl.error) {
output += 'Downloading ' + path.basename(dl.target) + '\n'
output += 'Error: ' + dl.error + '\n'
return
}
var pct = dl.percentage
var speed = dl.speed || 0
var total = dl.fileSize
totalSpeed += speed
var bar = Array(Math.floor(45 * pct / 100)).join('=') + '>'
while (bar.length < 45) bar += ' '
output += 'Downloading ' + path.basename(dl.target) + '\n' +
'[' + bar + '] ' + pct.toFixed(1) + '%'
if (total) output += ' of ' + prettyBytes(total)
output += ' (' + prettyBytes(speed) + '/s)\n'
})
if (rendered < downloads.length) output += '\n... and ' + (downloads.length - rendered) + ' more\n'
if (downloads.length > 1) output += '\nCombined Speed: ' + prettyBytes(totalSpeed) + '/s\n'
_log(output)
}
function startDownload (url, opts, cb) {
var targetName = path.basename(url).split('?')[0]
if (opts.singleTarget && opts.target) targetName = opts.target
var target = path.resolve(opts.dir || process.cwd(), targetName)
var origTarget = target
if (opts.tmpfile) {
target = target + '.tmp'
}
if (opts.resume) {
resume(url, opts, cb)
} else {
download(url, opts, cb)
}
var progressEmitter = new EventEmitter()
progressEmitter.target = target
progressEmitter.speed = 0
progressEmitter.percentage = 0
function onprogress (p) {
var pct = p.percentage
progressEmitter.progress = p
progressEmitter.percentage = pct
progressEmitter.emit('progress', p)
}
return progressEmitter
function resume (url, opts, cb) {
var onStat = function (err, stats) {
if (err && err.code === 'ENOENT') {
return download(url, opts, cb)
}
if (err) {
return cb(err)
}
var offset = stats.size
var req = request.get(url)
req.on('error', cb)
req.on('response', function (resp) {
resp.destroy()
var length = parseInt(resp.headers['content-length'], 10)
// file is already downloaded.
if (length === offset) {
onprogress({percentage: 100})
return cb()
}
if (!isNaN(length) && length > offset && /bytes/.test(resp.headers['accept-ranges'])) {
opts.range = [offset, length]
}
download(url, opts, cb)
})
}
if (opts.tmpfile) {
fs.stat(origTarget, function (err, origStats) {
if (err && err.code === 'ENOENT') {
fs.stat(target, onStat)
} else {
// file is already downloaded
onprogress({percentage: 100})
cb()
}
})
} else {
fs.stat(target, onStat)
}
}
function download (url, opts, cb) {
var headers = opts.headers || {}
if (opts.range) {
headers.Range = 'bytes=' + opts.range[0] + '-' + opts.range[1]
}
var read = request(url, { headers: headers })
read.on('error', cb)
read.on('response', function (resp) {
debug('response', url, resp.statusCode)
if (resp.statusCode > 299 && !opts.force) return cb(new Error('GET ' + url + ' returned ' + resp.statusCode))
var write = fs.createWriteStream(target, {flags: opts.resume ? 'a' : 'w'})
write.on('error', cb)
write.on('finish', async () => {
if (opts.tmpfile) {
fs.rename(target, origTarget, cb)
} else {
process.nextTick(cb)
}
})
var fullLen
var contentLen = Number(resp.headers['content-length'])
var range = resp.headers['content-range']
if (range) {
fullLen = Number(range.split('/')[1])
} else {
fullLen = contentLen
}
progressEmitter.fileSize = fullLen
if (range) {
var downloaded = fullLen - contentLen
}
var progressStream = progress({ length: fullLen, transferred: downloaded }, onprogress)
progressEmitter.emit('start', progressStream)
resp
.pipe(progressStream)
.pipe(write)
})
}
}
}