forked from sindresorhus/electron-dl
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
209 lines (173 loc) · 5.93 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
'use strict';
const path = require('path');
const electron = require('electron');
const unusedFilename = require('unused-filename');
const pupa = require('pupa');
const extName = require('ext-name');
const _ = require('lodash');
const {app, shell} = electron;
const CONFIG = {
NO_PROGRESS_THRESHOLD: 20,
DOWNLOAD_MAX_RETRY: 3
};
function getFilenameFromMime(name, mime) {
const exts = extName.mime(mime);
if (exts.length !== 1) {
return name;
}
return `${name}.${exts[0].ext}`;
}
const sessionListenerMap = new Map();
const handlerMap = new Map();
const downloadItems = new Set();
let receivedBytes = 0;
let completedBytes = 0;
let totalBytes = 0;
const activeDownloadItems = () => downloadItems.size;
const progressDownloadItems = function (item) {
if (item) {
return item.getReceivedBytes() / item.getTotalBytes();
}
return receivedBytes / totalBytes;
};
function registerListener(session) {
const listener = (e, item, webContents) => {
const urlChains = item.getURLChain();
const originUrl = _.first(urlChains);
const key = decodeURIComponent(originUrl);
const defaultHanlder = {
options: {},
resolve: () => { },
reject: () => { }
};
var handlers = handlerMap.get(key) || defaultHanlder;
const {options, resolve, reject} = handlers;
downloadItems.add(item);
totalBytes += item.getTotalBytes();
let hostWebContents = webContents;
if (webContents.getType() === 'webview') {
({hostWebContents} = webContents);
}
const win = electron.BrowserWindow.fromWebContents(hostWebContents);
const dir = options.directory || app.getPath('downloads');
let filePath;
if (options.filename) {
filePath = path.join(dir, options.filename);
} else {
const filename = item.getFilename();
const name = path.extname(filename) ? filename : getFilenameFromMime(filename, item.getMimeType());
filePath = unusedFilename.sync(path.join(dir, name));
}
const errorMessage = options.errorMessage || 'The download of {filename} was interrupted';
const errorTitle = options.errorTitle || 'Download Error';
if (!options.saveAs) {
item.setSavePath(filePath);
}
item.on('updated', (e, state) => {
if (handlers.retryCount >= CONFIG.DOWNLOAD_MAX_RETRY) {
item.removeAllListeners();
_resetStats(win);
return reject(new Error(`Failed to start download for ${key}`));
}
if (state === 'interrupted' && item.canResume()) {
// This may a flash network interuption, we can retry a few times
setTimeout(() => {
handlers.retryCount++;
item.resume();
}, 5000);
return;
}
var updateProgress = progressDownloadItems(item);
if (updateProgress === handlers.progress) {
// No download progress, the download maybe passively interupted (network issue)
// Electron does not raised interupted state for this case at the moment, so we handle ourself
if (handlers.noProgress === CONFIG.NO_PROGRESS_THRESHOLD) {
item.removeAllListeners();
_resetStats(win);
return reject(new Error(`Failed to download for ${key}`));
}
handlers.noProgress++;
} else {
handlers.progress = updateProgress;
handlers.noProgress = 0;
}
receivedBytes = [...downloadItems].reduce((receivedBytes, item) => {
receivedBytes += item.getReceivedBytes();
return receivedBytes;
}, completedBytes);
if (['darwin', 'linux'].includes(process.platform)) {
app.setBadgeCount(activeDownloadItems());
}
if (!win.isDestroyed()) {
win.setProgressBar(progressDownloadItems());
}
if (typeof options.onProgress === 'function') {
options.onProgress(progressDownloadItems(item));
}
});
item.once('done', (e, state) => {
completedBytes += item.getTotalBytes();
item.removeAllListeners();
downloadItems.delete(item);
if (['darwin', 'linux'].includes(process.platform)) {
app.setBadgeCount(activeDownloadItems());
}
if (!activeDownloadItems()) {
_resetStats(win);
}
if (state === 'interrupted') {
const message = pupa(errorMessage, {filename: item.getFilename()});
electron.dialog.showErrorBox(errorTitle, message);
reject(new Error(message));
} else if (state === 'cancelled') {
_resetStats(win);
reject(new Error('The download has been cancelled'));
} else if (state === 'completed') {
if (process.platform === 'darwin') {
app.dock.downloadFinished(filePath);
}
if (options.openFolderWhenDone) {
shell.showItemInFolder(filePath);
}
resolve(item);
}
if (handlerMap.has(key)) {
handlerMap.delete(key);
}
});
};
return listener;
}
function unregisterListener (session) {
if (sessionListenerMap.has(session)) {
sessionListenerMap.delete(session);
}
}
function _resetStats (win) {
if (win && !win.isDestroyed()) {
win.setProgressBar(-1);
}
receivedBytes = 0;
completedBytes = 0;
totalBytes = 0;
downloadItems.clear();
}
module.exports = (options = {}) => {
app.on('session-created', session => {
registerListener(session, options);
app.on('close', () => unregisterListener(session));
});
};
module.exports.download = (win, url, options) => new Promise((resolve, reject) => {
options = Object.assign({}, options, {unregisterWhenDone: true});
const key = decodeURIComponent(url);
handlerMap.set(key, {options, resolve, reject, progress: 0, retryCount: 0, noProgress: 0});
var session = win.webContents.session;
// Only need to register listener for new window/session
if (!sessionListenerMap.get(session)) {
sessionListenerMap.set(session, true);
session.on('will-download', registerListener(session));
win.on('close', () => unregisterListener(session));
}
win.webContents.downloadURL(url);
});