-
-
Notifications
You must be signed in to change notification settings - Fork 138
/
index.js
53 lines (42 loc) · 1.32 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
'use strict';
const path = require('path');
const electron = require('electron');
const app = electron.app;
function registerListener(win, opts = {}) {
const listener = (e, item, webContents) => {
const totalBytes = item.getTotalBytes();
const filePath = path.join(app.getPath('downloads'), item.getFilename());
item.setSavePath(filePath);
// TODO: use mime type checking for file extension when no extension can be inferred
// item.getMimeType()
item.on('updated', () => {
win.setProgressBar(item.getReceivedBytes() / totalBytes);
});
item.on('done', (e, state) => {
if (!win.isDestroyed()) {
win.setProgressBar(-1);
}
if (state === 'interrupted') {
electron.dialog.showErrorBox('Download error', `The download of ${item.getFilename()} was interrupted`);
}
if (state === 'completed') {
if (process.platform === 'darwin') {
app.dock.downloadFinished(filePath);
}
if (opts.unregisterWhenDone) {
webContents.session.removeListener('will-download', listener);
}
}
});
};
win.webContents.session.on('will-download', listener);
}
module.exports = () => {
app.on('browser-window-created', (e, win) => {
registerListener(win);
});
};
module.exports.download = (win, url) => {
registerListener(win, {unregisterWhenDone: true});
win.webContents.downloadURL(url);
};