forked from sindresorhus/electron-dl
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
182 lines (150 loc) · 5.14 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
'use strict';
const path = require('path');
const { app, BrowserWindow, shell, dialog } = require('electron');
const unusedFilename = require('unused-filename');
const pupa = require('pupa');
const extName = require('ext-name');
const getFilenameFromMime = (name, mime) => {
const extensions = extName.mime(mime);
if (extensions.length !== 1) {
return name;
}
return `${name}.${extensions[0].ext}`;
};
const downloadItems = new Map();
const activeDownloadItems = () => downloadItems.size;
function registerListener(session, options, callback = () => {}) {
const progressDownloadItems = () => {
const bytes = [...downloadItems].reduce(
({ totalBytes, receivedBytes }, file) => {
const [, { item }] = file;
totalBytes += item.getTotalBytes();
receivedBytes += item.getReceivedBytes();
return {
totalBytes,
receivedBytes
};
}, { totalBytes: 0, receivedBytes: 0 }
);
return bytes.receivedBytes / bytes.totalBytes;
};
const listener = (event, item, webContents) => {
// For some reason the 'will-download' event is triggered
// more than once for certain items when downloading multiple files,
// so this makes sure the item is "replace" with the last item,
// this become useful on 'updated' event.
if (downloadItems.has(item.getFilename())) {
downloadItems.delete(item.getFilename());
}
// Setting the item with it's options for future references.
// This avoids this bug found in electro-dl (https://github.com/sindresorhus/electron-dl/issues/83)
// which reports the wrong progress when downloading multiple items
// on item's 'updated' event.
downloadItems.set(item.getFilename(), {
options,
item
});
let hostWebContents = webContents;
if (webContents.getType() === 'webview') {
({ hostWebContents } = webContents);
}
const window_ = BrowserWindow.fromWebContents(hostWebContents);
const directory = options.directory || app.getPath('downloads');
let filePath;
if (options.filename) {
filePath = path.join(directory, options.filename);
} else {
const filename = item.getFilename();
const name = path.extname(filename) ? filename : getFilenameFromMime(filename, item.getMimeType());
filePath = unusedFilename.sync(path.join(directory, name));
}
const errorMessage = options.errorMessage || 'The download of {filename} was interrupted';
const errorTitle = options.errorTitle || 'Download Error';
if (!options.saveAs) {
item.setSavePath(filePath);
}
if (typeof options.onStarted === 'function') {
options.onStarted(item);
}
item.on('updated', (event, state) => {
const { options } = downloadItems.get(item.getFilename());
if (state === 'progressing') {
if (options.showBadge && ['darwin', 'linux'].includes(process.platform)) {
app.badgeCount = activeDownloadItems();
}
if (!window_.isDestroyed()) {
window_.setProgressBar(progressDownloadItems());
}
if (typeof options.onProgress === 'function') {
options.onProgress({
percent: item.getTotalBytes() ? item.getReceivedBytes() / item.getTotalBytes() : 0,
transferredBytes: item.getReceivedBytes(),
totalBytes: item.getTotalBytes()
});
}
} else if (state === 'interrupted') {
// ---- NOT FULLY IMPLEMENTED ---
// The download has interrupted and can be resumed.
// Read: https://www.electronjs.org/docs/api/download-item#downloaditemresume
callback(null, item);
}
});
item.on('done', (event, state) => {
downloadItems.delete(item.getFilename());
// Apparently this only works on Mac and Linux/Unity.
// The only problem is that Unity is no more
// so in Linux/Gnome for example, app.badgeCount is always equal to zero "0"
if (options.showBadge && ['darwin', 'linux'].includes(process.platform)) {
app.badgeCount = activeDownloadItems();
}
if (!window_.isDestroyed() && !activeDownloadItems()) {
window_.setProgressBar(-1);
}
if (options.unregisterWhenDone) {
session.removeListener('will-download', listener);
}
if (state === 'cancelled') {
if (typeof options.onCancel === 'function') {
options.onCancel(item);
}
} else if (state === 'interrupted') {
const message = pupa(errorMessage, {
filename: item.getFilename()
});
dialog.showErrorBox(errorTitle, message);
callback(new Error(message));
} else if (state === 'completed') {
if (process.platform === 'darwin') {
app.dock.downloadFinished(filePath);
}
if (options.openFolderWhenDone) {
shell.showItemInFolder(path.join(directory, item.getFilename()));
}
callback(null, item);
}
});
};
session.on('will-download', listener);
}
module.exports = (options = {}) => {
app.on('session-created', session => {
registerListener(session, options);
});
};
module.exports.activeDownloadItems = activeDownloadItems;
module.exports.download = (window_, url, options) =>
new Promise((resolve, reject) => {
options = {
showBadge: true,
...options,
unregisterWhenDone: true
};
registerListener(window_.webContents.session, options, (error, item) => {
if (error) {
reject(error);
} else {
resolve(item);
}
});
window_.webContents.downloadURL(url);
});