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

Support multiple download #1

Merged
merged 3 commits into from
Jul 2, 2018
Merged
Show file tree
Hide file tree
Changes from 2 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
91 changes: 52 additions & 39 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ 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;

Expand All @@ -17,19 +18,32 @@ function getFilenameFromMime(name, mime) {
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 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: () => { }
};
const {options, resolve, reject} = handlerMap.get(key) || defaultHanlder;

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

Expand Down Expand Up @@ -57,17 +71,13 @@ function registerListener(session, options, cb = () => {}) {
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)) {
if (['darwin', 'linux'].includes(process.platform)) {
app.setBadgeCount(activeDownloadItems());
}

Expand All @@ -76,15 +86,15 @@ function registerListener(session, options, cb = () => {}) {
}

if (typeof options.onProgress === 'function') {
options.onProgress(progressDownloadItems());
options.onProgress(progressDownloadItems(item));
}
});

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

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

Expand All @@ -95,51 +105,54 @@ function registerListener(session, options, cb = () => {}) {
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') {
if (state === 'interrupted') {
const message = pupa(errorMessage, {filename: item.getFilename()});
electron.dialog.showErrorBox(errorTitle, message);
cb(new Error(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 (options.openFolderWhenDone) {
shell.showItemInFolder(path.join(dir, item.getFilename()));
shell.showItemInFolder(filePath);
}

cb(null, item);
resolve(item);
}
if (handlerMap.has(key)) {
handlerMap.delete(key);
}
});
};

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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks like a session leak where we'll never remove this?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't worry, We just set it one time because of condition if (!sessionListenerMap.get(session))

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure what you meant. if we don't have code to remove this. sessionListenerMap would just keep growing infinitely = session leak.

We need to also remove the session when its no longer used?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we just have 1 session / electron windows?. This sessionListenerMap will destroyed when session destroy?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

session is dead doesn't mean it'll be removed from the sessionListenerMap, right? So we should listen to window close event and remove session from sessionListenerMap?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I updated the code to delete session in sessionListenerMap before windows close event

session.on('will-download', listener);
}
}

function unregisterListener (session) {
if (sessionListenerMap.has(session)) {
sessionListenerMap.delete(session);
}
}

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});

registerListener(win.webContents.session, options, (err, item) => {
if (err) {
reject(err);
} else {
resolve(item);
}
});
handlerMap.set(decodeURIComponent(url), {options, resolve, reject});

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we want to also rename url to key? Do we actually use the url?

registerListener(win.webContents.session);
win.on('close', () => unregisterListener(win.webContents.session));

win.webContents.downloadURL(url);
});
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
],
"dependencies": {
"ext-name": "^5.0.0",
"lodash": "^4.17.10",
"pupa": "^1.0.0",
"unused-filename": "^1.0.0"
},
Expand Down