1 | var __rest = (this && this.__rest) || function (s, e) {
|
2 | var t = {};
|
3 | for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
4 | t[p] = s[p];
|
5 | if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
6 | for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
7 | if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
8 | t[p[i]] = s[p[i]];
|
9 | }
|
10 | return t;
|
11 | };
|
12 | import * as fs from 'fs-extra';
|
13 | import * as got from 'got';
|
14 | import * as path from 'path';
|
15 | import * as ProgressBar from 'progress';
|
16 | const PROGRESS_BAR_DELAY_IN_SECONDS = 30;
|
17 | export class GotDownloader {
|
18 | async download(url, targetFilePath, options) {
|
19 | if (!options) {
|
20 | options = {};
|
21 | }
|
22 | const { quiet, getProgressCallback } = options, gotOptions = __rest(options, ["quiet", "getProgressCallback"]);
|
23 | let downloadCompleted = false;
|
24 | let bar;
|
25 | let progressPercent;
|
26 | let timeout = undefined;
|
27 | await fs.mkdirp(path.dirname(targetFilePath));
|
28 | const writeStream = fs.createWriteStream(targetFilePath);
|
29 | if (!quiet || !process.env.ELECTRON_GET_NO_PROGRESS) {
|
30 | const start = new Date();
|
31 | timeout = setTimeout(() => {
|
32 | if (!downloadCompleted) {
|
33 | bar = new ProgressBar(`Downloading ${path.basename(url)}: [:bar] :percent ETA: :eta seconds `, {
|
34 | curr: progressPercent,
|
35 | total: 100,
|
36 | });
|
37 |
|
38 |
|
39 | bar.start = start;
|
40 | }
|
41 | }, PROGRESS_BAR_DELAY_IN_SECONDS * 1000);
|
42 | }
|
43 | await new Promise((resolve, reject) => {
|
44 | const downloadStream = got.stream(url, gotOptions);
|
45 | downloadStream.on('downloadProgress', async (progress) => {
|
46 | progressPercent = progress.percent;
|
47 | if (bar) {
|
48 | bar.update(progress.percent);
|
49 | }
|
50 | if (getProgressCallback) {
|
51 | await getProgressCallback(progress);
|
52 | }
|
53 | });
|
54 | downloadStream.on('error', error => {
|
55 | if (error.name === 'HTTPError' && error.statusCode === 404) {
|
56 | error.message += ` for ${error.url}`;
|
57 | }
|
58 | if (writeStream.destroy) {
|
59 | writeStream.destroy(error);
|
60 | }
|
61 | reject(error);
|
62 | });
|
63 | writeStream.on('error', error => reject(error));
|
64 | writeStream.on('close', () => resolve());
|
65 | downloadStream.pipe(writeStream);
|
66 | });
|
67 | downloadCompleted = true;
|
68 | if (timeout) {
|
69 | clearTimeout(timeout);
|
70 | }
|
71 | }
|
72 | }
|
73 |
|
\ | No newline at end of file |