1 | "use strict";
|
2 | const https = require("https");
|
3 | const fs_1 = require("fs");
|
4 | const url_1 = require("url");
|
5 | const bluebird_1 = require("bluebird");
|
6 | const maxRedirects = 10;
|
7 | exports.download = bluebird_1.Promise.promisify(_download);
|
8 | function _download(url, destination, callback) {
|
9 | doDownload(url, destination, 0, callback);
|
10 | }
|
11 | function addTimeOutHandler(request, callback) {
|
12 | request.on("socket", function (socket) {
|
13 | socket.setTimeout(60 * 1000, () => {
|
14 | callback("Request timed out");
|
15 | request.abort();
|
16 | });
|
17 | });
|
18 | }
|
19 | exports.addTimeOutHandler = addTimeOutHandler;
|
20 | function doDownload(url, destination, redirectCount, callback) {
|
21 | const parsedUrl = url_1.parse(url);
|
22 | const request = https.request({
|
23 | hostname: parsedUrl.hostname,
|
24 | path: parsedUrl.path,
|
25 | headers: {
|
26 | "User-Agent": "electron-complete-builder"
|
27 | }
|
28 | }, (response) => {
|
29 | if (response.statusCode >= 400) {
|
30 | callback(new Error("Request error, status " + response.statusCode + ": " + response.statusMessage));
|
31 | return;
|
32 | }
|
33 | const redirectUrl = response.headers.location;
|
34 | if (redirectUrl != null) {
|
35 | if (redirectCount < maxRedirects) {
|
36 | doDownload(redirectUrl, destination, redirectCount++, callback);
|
37 | }
|
38 | else {
|
39 | callback(new Error("Too many redirects (> " + maxRedirects + ")"));
|
40 | }
|
41 | return;
|
42 | }
|
43 | const downloadStream = fs_1.createWriteStream(destination);
|
44 | response.pipe(downloadStream);
|
45 | downloadStream.on("finish", () => downloadStream.close(callback));
|
46 | let ended = false;
|
47 | response.on("end", () => {
|
48 | ended = true;
|
49 | });
|
50 | response.on("close", () => {
|
51 | if (!ended) {
|
52 | callback(new Error("Request aborted"));
|
53 | }
|
54 | });
|
55 | });
|
56 | addTimeOutHandler(request, callback);
|
57 | request.on("error", callback);
|
58 | request.end();
|
59 | }
|
60 |
|
\ | No newline at end of file |