forked from ibrod83/nodejs-file-downloader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Download.js
384 lines (275 loc) · 10.1 KB
/
Download.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
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
const fs = require('fs');
const http = require('http')//For jsdoc
const IncomingMessage = http.IncomingMessage
const makeRequest = require('./makeRequest');
const stream = require('stream');
var HttpsProxyAgent = require('https-proxy-agent');
const { Transform } = require('stream')
const util = require('util');
const FileProcessor = require('./utils/FileProcessor');
const pipelinePromisified = util.promisify(stream.pipeline);
const mkdir = util.promisify(fs.mkdir);
const writeFile = util.promisify(fs.writeFile);
const { deduceFileName, exists } = require('./utils/fileName');
const { isJson } = require('./utils/string');
const unlink = util.promisify(fs.unlink)
const rename = util.promisify(fs.rename)
module.exports = class Download {
/**
*
* @param {object} config
* @param {string} config.url
* @param {string} [config.directory]
* @param {string} [config.fileName = undefined]
* @param {boolean } [config.cloneFiles=true]
* @param {boolean} [config.skipExistingFileName = false]
* @param {number} [config.timeout=6000]
* @param {object} [config.headers = undefined]
* @param {object} [config.httpsAgent = undefined]
* @param {string} [config.proxy = undefined]
* @param {function} [config.onResponse = undefined]
* @param {function} [config.onBeforeSave = undefined]
* @param {function} [config.onProgress = undefined]
* @param {boolean} [config.shouldBufferResponse = false]
* @param {boolean} [config.useSynchronousMode = false]
*/
constructor(config) {
const defaultConfig = {
directory: './',
fileName: undefined,
timeout: 6000,
useSynchronousMode: false,
httpsAgent: undefined,
proxy: undefined,
headers: undefined,
cloneFiles: true,
skipExistingFileName: false,
shouldBufferResponse: false,
onResponse: undefined,
onBeforeSave: undefined,
onProgress: undefined
}
this.config = {
...defaultConfig,
...config
}
this.isCancelled = false;
this.cancelCb = null;//Function from makeRequest, to cancel the download.
this.percentage = 0;
this.fileSize = null;
this.currentDataSize = 0;
this.originalResponse = null;//The IncomingMessage read stream.
}
/**
* The entire download process.
* @return {Promise<void>}
*/
async start() {
await this._verifyDirectoryExists(this.config.directory)
if (this.config.fileName && this.config.skipExistingFileName) {
if (await exists(this.config.directory + '/' + this.config.fileName)) {
return;
}
}
try {
const { dataStream, originalResponse } = await this._request();
this.originalResponse = originalResponse;
if (originalResponse.statusCode > 226) {
const error = await this._createErrorObject(dataStream,originalResponse)
throw error;
}
if (this.config.onResponse) {
const shouldContinue = await this.config.onResponse(originalResponse);
if (shouldContinue === false) {
return;
}
}
await this._save({ dataStream, originalResponse })
} catch (error) {
if (this.isCancelled) {
const customError = new Error('Request cancelled')
customError.code = 'ERR_REQUEST_CANCELLED'
throw customError
}
throw error;
}
}
async _createErrorObject(dataStream, originalResponse) {
const responseString = await this._getStringFromStream(dataStream);
const error = new Error(`Request failed with status code ${originalResponse.statusCode}`)
error.statusCode = originalResponse.statusCode
error.response = originalResponse
error.responseBody = isJson(responseString) ? JSON.parse(responseString) : responseString
return error;
}
async _getStringFromStream(stream) {
const buffer = await this._createBufferFromResponseStream(stream);
return buffer.toString();
}
/**
*
* @param {string} directory
*/
async _verifyDirectoryExists(directory) {
await mkdir(directory, { recursive: true });
}
/**
* @return {Promise<{dataStream:stream.Readable,originalResponse:IncomingMessage}}
*/
async _request() {
const { dataStream, originalResponse } = await this._makeRequest();
const headers = originalResponse.headers;
const contentLength = headers['content-length'] || headers['Content-Length'];
this.fileSize = parseInt(contentLength);
return { dataStream, originalResponse }
}
/**
* @param {Promise<{dataStream:stream.Readable,originalResponse:IncomingMessage}}
* @return {Promise<void>}
*/
async _save({ dataStream, originalResponse }) {
try {
let { finalFileName, originalFileName } = await this._getFileName(originalResponse.headers);
if (this.config.skipExistingFileName && await exists(this.config.directory + '/' + originalFileName)) {
// will skip this request
return;
}
if (this.config.onBeforeSave) {
const clientOverideName = await this.config.onBeforeSave(finalFileName)
if (clientOverideName && typeof clientOverideName === 'string') {
finalFileName = clientOverideName;
}
}
const finalPath = `${this.config.directory}/${finalFileName}`;
var tempPath = this._getTempFilePath(finalPath);
if (this.config.shouldBufferResponse) {
const buffer = await this._createBufferFromResponseStream(dataStream);
await this._saveFromBuffer(buffer, tempPath);
} else {
await this._saveFromReadableStream(dataStream, tempPath);
}
await this._renameTempFileToFinalName(tempPath, finalPath)
} catch (error) {
if (!this.config.shouldBufferResponse)
await this._removeFailedFile(tempPath)
throw error;
}
}
/**
*
* @return {Promise<{dataStream:stream.Readable,originalResponse:IncomingMessage}}
*/
async _makeRequest() {
const { timeout, headers, proxy, url, httpsAgent } = this.config;
const options = {
timeout,
headers
}
if (httpsAgent) {
options.agent = httpsAgent;
}
else if (proxy) {
options.agent = new HttpsProxyAgent(proxy)
}
const { makeRequestIter, cancel, } = makeRequest(url, options)
this.cancelCb = cancel
const { dataStream, originalResponse, } = await makeRequestIter()
return { dataStream, originalResponse }
}
/**
*
* @param {string} fullPath
* @return {Promie<WritableStream>}
*/
_createWriteStream(fullPath) {
return fs.createWriteStream(fullPath)
}
/**
*
* @param {stream.Readable} stream
* @returns
*/
async _createBufferFromResponseStream(stream) {
const chunks = []
for await (let chunk of stream) {
chunks.push(chunk)
}
const buffer = Buffer.concat(chunks)
return buffer;
}
_getProgressStream() {
const that = this;
const progress = new Transform({
transform(chunk, encoding, callback) {
that.currentDataSize += chunk.byteLength;
if (that.fileSize) {
that.percentage = ((that.currentDataSize / that.fileSize) * 100).toFixed(2)
} else {
that.percentage = NaN
}
const remainingFracture = (100 - that.percentage) / 100;
const remainingSize = Math.round(remainingFracture * that.fileSize);
if (that.config.onProgress) {
that.config.onProgress(that.percentage, chunk, remainingSize);
}
// Push the data onto the readable queue.
callback(null, chunk);
}
});
return progress;
}
async _pipeStreams(arrayOfStreams) {
await pipelinePromisified(...arrayOfStreams);
}
async _saveFromReadableStream(read, path) {
const streams = [read];
const write = this._createWriteStream(path)
if (this.config.onProgress) {
const progressStream = this._getProgressStream()
streams.push(progressStream);
}
streams.push(write)
await this._pipeStreams(streams)
}
async _saveFromBuffer(buffer, path) {
await writeFile(path, buffer)
}
async _removeFailedFile(path) {
await unlink(path);
}
async _renameTempFileToFinalName(temp, final) {
await rename(temp, final)
}
/**
*
* @param {string} finalpath
*/
_getTempFilePath(finalpath) {
return `${finalpath}.download`;
}
/**
* @param {object} responseHeaders
*/
async _getFileName(responseHeaders) {
let originalFileName;
let finalFileName;
if (this.config.fileName) {
originalFileName = this.config.fileName
} else {
originalFileName = deduceFileName(this.config.url, responseHeaders)
}
if (this.config.cloneFiles === true) {
var fileProcessor = new FileProcessor({ useSynchronousMode: this.config.useSynchronousMode, fileName: originalFileName, path: this.config.directory })
finalFileName = await fileProcessor.getAvailableFileName()
} else {
finalFileName = originalFileName
}
return { finalFileName, originalFileName };
}
cancel() {
if (this.cancelCb) {
this.isCancelled = true;
this.cancelCb()
}
}
}