forked from sindresorhus/electron-dl
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
165 lines (133 loc) · 4.54 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
'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');
function getFilenameFromMime(name, mime) {
const exts = extName.mime(mime);
if (exts.length !== 1) {
return name;
}
return `${name}.${exts[0].ext}`;
}
function registerListener(session, options, cb = () => {}) {
const downloadItems = new Set();
let receivedBytes = 0;
let completedBytes = 0;
let totalBytes = 0;
const activeDownloadItems = () => downloadItems.size;
const progressDownloadItems = () => receivedBytes / totalBytes;
options = Object.assign({
showBadge: true
}, options);
const listener = (e, item, webContents) => {
downloadItems.add(item);
totalBytes += item.getTotalBytes();
let hostWebContents = webContents;
if (webContents.getType() === 'webview') {
({hostWebContents} = webContents);
}
const win = BrowserWindow.fromWebContents(hostWebContents);
const dir = options.directory || app.getPath('downloads');
let filePath;
if (options.filename) {
filePath = path.join(dir, options.filename);
} else {
let filename = item.getFilename();
const extension = filename.lastIndexOf(".") > 0 ? `.${filename.substr(filename.lastIndexOf(".") + 1)}` : '';
if (filename.length > 200) filename = `${filename.substring(0, 200)}.${extension}`;
const name = path.extname(filename) ? filename : getFilenameFromMime(filename, item.getMimeType());
filePath = unusedFilename.sync(path.join(dir, name));
}
const extension = filePath.lastIndexOf(".") > 0 ? `.${filePath.substr(filePath.lastIndexOf(".") + 1)}` : '';
const errorMessage = options.errorMessage || 'The download of {filename} was interrupted';
const errorTitle = options.errorTitle || 'Download Error';
if (options.saveAs) {
const path = dialog.showSaveDialogSync(win, { defaultPath: `${filePath}` });
path === undefined ? item.cancel() : item.setSavePath(path.lastIndexOf(".") < 0 ? `${path}${extension}` : path);
} else {
item.setSavePath(filePath);
}
if (typeof options.onStarted === 'function') {
options.onStarted(item);
}
item.on('updated', () => {
receivedBytes = [...downloadItems].reduce((receivedBytes, item) => {
receivedBytes += item.getReceivedBytes();
return receivedBytes;
}, completedBytes);
if (options.showBadge && ['darwin', 'linux'].includes(process.platform)) {
app.setBadgeCount(activeDownloadItems());
}
if (!win.isDestroyed()) {
win.setProgressBar(progressDownloadItems());
}
if (typeof options.onProgress === 'function') {
options.onProgress(progressDownloadItems());
}
});
item.on('done', async (event, state) => {
completedBytes += item.getTotalBytes();
downloadItems.delete(item);
if (options.showBadge && ['darwin', 'linux'].includes(process.platform)) {
app.setBadgeCount(activeDownloadItems());
}
if (!win.isDestroyed() && !activeDownloadItems()) {
win.setProgressBar(-1);
receivedBytes = 0;
completedBytes = 0;
totalBytes = 0;
}
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);
cb(new Error(message));
} else if (state === 'completed') {
if (process.platform === 'darwin') {
app.dock.downloadFinished(item.getSavePath());
}
if (options.openFileWhenDone) {
try {
await shell.openPath(item.getSavePath());
} catch (err) {
console.error(err)
}
}
if (options.openFolderWhenDone) {
shell.showItemInFolder(item.getSavePath());
}
if (typeof options.onDone === 'function') {
options.onDone(item.getSavePath());
}
cb(null, item);
}
});
};
session.on('will-download', listener);
}
module.exports = (options = {}) => {
app.on('session-created', session => {
registerListener(session, options);
});
};
// TODO: Remove this for the next major release
module.exports.default = module.exports;
module.exports.download = (win, url, options) => new Promise((resolve, reject) => {
options = Object.assign({}, options, {unregisterWhenDone: true});
registerListener(win.webContents.session, options, (err, item) => {
if (err) {
reject(err);
} else {
resolve(item);
}
});
win.webContents.downloadURL(url);
});