Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: avoid create multiple listener #36

Closed
wants to merge 6 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
237 changes: 123 additions & 114 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
'use strict';
const path = require('path');
const electron = require('electron');
const unusedFilename = require('unused-filename');
Expand All @@ -9,126 +8,136 @@ const app = electron.app;
const shell = electron.shell;

function getFilenameFromMime(name, mime) {
const exts = extName.mime(mime);
const exts = extName.mime(mime);

if (exts.length !== 1) {
return name;
}
if (exts.length !== 1) {
return name;
}

return `${name}.${exts[0].ext}`;
return `${name}.${exts[0].ext}`;
}

function registerListener(session, opts = {}, cb = () => {}) {
const downloadItems = new Set();
let receivedBytes = 0;
let completedBytes = 0;
let totalBytes = 0;
const activeDownloadItems = () => downloadItems.size;
const progressDownloadItems = () => receivedBytes / totalBytes;

const listener = (e, item, webContents) => {
downloadItems.add(item);
totalBytes += item.getTotalBytes();

let hostWebContents = webContents;
if (webContents.getType() === 'webview') {
hostWebContents = webContents.hostWebContents;
}
const win = electron.BrowserWindow.fromWebContents(hostWebContents);

const dir = opts.directory || app.getPath('downloads');
let filePath;
if (opts.filename) {
filePath = path.join(dir, opts.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 = opts.errorMessage || 'The download of {filename} was interrupted';
const errorTitle = opts.errorTitle || 'Download Error';

if (!opts.saveAs) {
item.setSavePath(filePath);
}

item.on('updated', () => {
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 opts.onProgress === 'function') {
opts.onProgress(progressDownloadItems());
}
});

item.on('done', (e, state) => {
completedBytes += item.getTotalBytes();
downloadItems.delete(item);

if (['darwin', 'linux'].includes(process.platform)) {
app.setBadgeCount(activeDownloadItems());
}

if (!win.isDestroyed() && !activeDownloadItems()) {
win.setProgressBar(-1);
receivedBytes = 0;
completedBytes = 0;
totalBytes = 0;
}

if (state === 'interrupted') {
const message = pupa(errorMessage, {filename: item.getFilename()});
electron.dialog.showErrorBox(errorTitle, message);
cb(new Error(message));
} else if (state === 'completed') {
if (process.platform === 'darwin') {
app.dock.downloadFinished(filePath);
}

if (opts.openFolderWhenDone) {
shell.showItemInFolder(filePath);
}

if (opts.unregisterWhenDone) {
session.removeListener('will-download', listener);
}

cb(null, item);
}
});
};

session.on('will-download', listener);
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 = () => receivedBytes / totalBytes;

function registerListener(session) {
const listener = (e, item, webContents) => {
const url = decodeURIComponent(item.getURL());
const defaultHanlder = {
opts: {},
resolve: () => {},
reject: () => {},
};
const { opts, resolve, reject } = handlerMap.get(url) || defaultHanlder;

downloadItems.add(item);
totalBytes += item.getTotalBytes();

let hostWebContents = webContents;
if (webContents.getType() === 'webview') {
hostWebContents = webContents.hostWebContents;
}
const win = electron.BrowserWindow.fromWebContents(hostWebContents);

const dir = opts.directory || app.getPath('downloads');
let filePath;
if (opts.filename) {
filePath = path.join(dir, opts.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 =
opts.errorMessage || 'The download of {filename} was interrupted';
const errorTitle = opts.errorTitle || 'Download Error';

if (!opts.saveAs) {
item.setSavePath(filePath);
}

item.on('updated', () => {
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 opts.onProgress === 'function') {
opts.onProgress(progressDownloadItems());
}
});

item.once('done', (e, state) => {
completedBytes += item.getTotalBytes();
downloadItems.delete(item);

if (['darwin', 'linux'].includes(process.platform)) {
app.setBadgeCount(activeDownloadItems());
}

if (!win.isDestroyed() && !activeDownloadItems()) {
win.setProgressBar(-1);
receivedBytes = 0;
completedBytes = 0;
totalBytes = 0;
}

if (state === 'interrupted') {
const message = pupa(errorMessage, { filename: item.getFilename() });
electron.dialog.showErrorBox(errorTitle, message);
reject(new Error(message));
} else if (state === 'cancelled') {
reject(new Error('The download has been cancelled'));
} else if (state === 'completed') {
if (process.platform === 'darwin') {
app.dock.downloadFinished(filePath);
}

if (opts.openFolderWhenDone) {
shell.showItemInFolder(filePath);
}

resolve(item);
}

if (handlerMap.has(url)) handlerMap.delete(url);
});
};

if (!sessionListenerMap.get(session)) {
sessionListenerMap.set(session, true);
session.on('will-download', listener);
}
}

module.exports = (opts = {}) => {
app.on('session-created', session => {
registerListener(session, opts);
});
app.on('session-created', session => {
registerListener(session, opts);
});
};

module.exports.download = (win, url, opts) => new Promise((resolve, reject) => {
opts = Object.assign({}, opts, {unregisterWhenDone: true});
module.exports.download = (win, url, opts) =>
new Promise((resolve, reject) => {
handlerMap.set(decodeURIComponent(url), { opts, resolve, reject });
registerListener(win.webContents.session);

registerListener(win.webContents.session, opts, (err, item) => {
if (err) {
reject(err);
} else {
resolve(item);
}
});

win.webContents.downloadURL(url);
});
win.webContents.downloadURL(url);
});