Giter Site home page Giter Site logo

danielnieto / electron-download-manager Goto Github PK

View Code? Open in Web Editor NEW
119.0 2.0 51.0 46 KB

Manage downloadItems from Electron's BrowserWindows without user interaction, allowing single file download and bulk downloading

License: MIT License

JavaScript 100.00%
electron downloadmanager bulk-download bulk downloaditem

electron-download-manager's People

Contributors

76200 avatar arthurlee avatar benji1 avatar cbh6 avatar cedced19 avatar danielnieto avatar erikkallen avatar marlon360 avatar mikewu-x2 avatar ndelvalle avatar riazxrazor avatar rugor avatar thejhnz avatar tripss avatar verbal-torment avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

electron-download-manager's Issues

Cannot read property 'getPath' of undefined

i am trying to use this package with electron-vue template but getting following error on Windows 10 machine

D:\Electron\Electron-vue-startup-template\node_modules\electron-download-manager\index.js:8 Uncaught TypeError: Cannot read property 'getPath' of undefined
    at Object.<anonymous> (D:\Electron\Electron-vue-startup-template\node_modules\electron-download-manager\index.js:8)
    at Object.<anonymous> (D:\Electron\Electron-vue-startup-template\node_modules\electron-download-manager\index.js:267)
    at Module._compile (internal/modules/cjs/loader.js:968)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:986)
    at Module.load (internal/modules/cjs/loader.js:816)
    at Module._load (internal/modules/cjs/loader.js:728)
    at Module._load (electron/js2c/asar.js:717)
    at Function.Module._load (electron/js2c/asar.js:717)
    at Module.require (internal/modules/cjs/loader.js:853)
    at require (internal/modules/cjs/helpers.js:74)

here is my package.json

{
  "name": "electron-vue-startup-template",
  "version": "0.0.1",
  "author": "",
  "description": "An electron-vue project",
  "license": null,
  "main": "./dist/electron/main.js",
  "scripts": {
    "build": "node .electron-vue/build.js && electron-builder",
    "build:dir": "node .electron-vue/build.js && electron-builder --dir",
    "build:clean": "cross-env BUILD_TARGET=clean node .electron-vue/build.js",
    "build:web": "cross-env BUILD_TARGET=web node .electron-vue/build.js",
    "dev": "node .electron-vue/dev-runner.js",
    "pack": "npm run pack:main && npm run pack:renderer",
    "pack:main": "cross-env NODE_ENV=production webpack --progress --colors --config .electron-vue/webpack.main.config.js",
    "pack:renderer": "cross-env NODE_ENV=production webpack --progress --colors --config .electron-vue/webpack.renderer.config.js",
    "postinstall": ""
  },
  "build": {
    "productName": "electron-vue-startup-template",
    "appId": "com.example.yourapp",
    "directories": {
      "output": "build"
    },
    "files": [
      "dist/electron/**/*"
    ],
    "dmg": {
      "contents": [
        {
          "x": 410,
          "y": 150,
          "type": "link",
          "path": "/Applications"
        },
        {
          "x": 130,
          "y": 150,
          "type": "file"
        }
      ]
    },
    "mac": {
      "icon": "build/icons/icon.icns"
    },
    "win": {
      "icon": "build/icons/icon.ico"
    },
    "linux": {
      "icon": "build/icons"
    }
  },
  "dependencies": {
    "axios": "^0.18.0",
    "electron-download-manager": "^2.1.2",
    "vue": "^2.5.16",
    "vue-electron": "^1.0.6",
    "vue-router": "^3.0.1",
    "vuex": "^3.0.1",
    "vuex-electron": "^1.0.0"
  },
  "devDependencies": {
    "ajv": "^6.5.0",
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.4",
    "babel-minify-webpack-plugin": "^0.3.1",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-stage-0": "^6.24.1",
    "babel-register": "^6.26.0",
    "cfonts": "^2.1.2",
    "chalk": "^2.4.1",
    "copy-webpack-plugin": "^5.1.1",
    "cross-env": "^5.1.6",
    "css-loader": "^3.4.2",
    "del": "^3.0.0",
    "devtron": "^1.4.0",
    "electron": "^8.0.2",
    "electron-builder": "^20.19.2",
    "electron-debug": "^1.5.0",
    "electron-devtools-installer": "^2.2.4",
    "file-loader": "^1.1.11",
    "html-webpack-plugin": "^3.2.0",
    "mini-css-extract-plugin": "0.4.0",
    "multispinner": "^0.2.1",
    "node-loader": "^0.6.0",
    "node-sass": "^4.9.2",
    "sass-loader": "^7.0.3",
    "style-loader": "^0.21.0",
    "url-loader": "^1.0.1",
    "vue-html-loader": "^1.2.4",
    "vue-loader": "^15.2.4",
    "vue-style-loader": "^4.1.0",
    "vue-template-compiler": "^2.5.16",
    "webpack": "^4.15.1",
    "webpack-cli": "^3.0.8",
    "webpack-dev-server": "^3.1.4",
    "webpack-hot-middleware": "^2.22.2",
    "webpack-merge": "^4.1.3"
  }
}

Saddenly "save dialog" open duration downloading

i try download multi files by .map and {download} function. but sometime save dialog open and try somthing called "download", how can i manage it?

downloadQueue.map(source => {
          DownloadManager.download({
            url: source.filename,
            path: source.type
          }, (error, finished, failed) => {
            if (finished) {
              repoDownloaded += 1;
            }
            return !error;
          });
          return true;
        });

File is removing on app close

Hi!

Building a download manager using electron and this lib. Facing an issue that if download is not finished and app was closed (or download is paused and app was closed) file is deleted immediately after app close.

Could you please help to prevent such a behavior?

Cannot catch net.request errors

Errors thrown from the net.request are not handled by the callback passed to the download method. When URL cannot be resolved or connection is refused, I'm getting javascript error from the main process (error box).

error-box

Just try to invoke download method with http://testnotresolved.com/file.zip URL.

Issues when using bulkDownload

Hi. I've been using this module for a little bit. It used to work alright. Now somethin weird is happening.
The files get downloaded no problem. After that I used to rewrite their names and be done with them.
Now, even after removing all of my custom code, the callback never gets called, even tho the files are downloaded.
I changed the whole callback to the documentation one. Yet no callback.
Any ideas?

remote.require("electron-download-manager").bulkDownload({
                            urls: offline_playlist_url,
                        }, function (error, finished, errors) {
                            if (error) {
                                console.log("finished: " + finished);
                                console.log("errors: " + errors);
                                return;
                            }

                            console.log("all finished");
                        })

Returns no console.log

Main process XHR requests are pending while downloading

I'm downloading big files from a renderer calling remote.require("electron-download-manager").download.
Everything works fine but all XHR requests made by the Main process after that the download has began remain in pending state until the dowload is completed.
Is there something I can do to allow the Main process to make requests and receive webservice results while downloading? Thanks

path error

Hello.
I am using this module well. Downloading is OK, but the following error occurs : Why is that?

Imgur

Thank you.

.zip file instant interrupt

Hello,

in custom function i have

DownloadManager.download({
            url: xxx,
            path: DOWNLOAD_DIR
        }, function (error, info) {
            if (error) {
                console.log(error);
                return;
            }

            console.log("DONE: " + info.url);
        });

but for some reason .zip file is instantly interrupted. From chrome i can download it normally.

Start downloading Patch.zip
Patch.zip does not exist, download it now
Error: The download of Patch.zip was interrupted
    at DownloadItem.<anonymous> (D:\app\node_modules\electron-download-manager\index.js:63:46)
    at DownloadItem.emit (events.js:194:13)

on webhost i have this

if (file_exists($file)) {
            header('Content-Description: File Transfer');
            //header('Content-Type: application/octet-stream');
            header("Content-type: application/zip");
            header('Content-Disposition: attachment; filename="' . $file . '"');
            header('Content-Transfer-Encoding: binary');
            header('Connection: Keep-Alive');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Content-Length: ' . sprintf("%u", filesize($file)));
            $fh = fopen($file, "rb");
            while (!feof($fh)) {
                echo fgets($fh);
                flush();
            }
            fclose($fh);
            exit;
        } else {
            header("HTTP/1.0 404 Not Found");
            exit('File not found!');
        }

Error if file name contains the % symbol

When I try to download a file with a name that contains a % symbol It will throw an error and then open the save dialog
image

The file I try to download https://files.beatconnect.io/b/639236+UNISON+SQUARE+GARDEN+-+10%25+roll%2C+10%25+romance+%28TV+Size%29.OuToU.osz

It happens when decodeURIComponent() is called here :

const itemFilename = decodeURIComponent(item.getFilename());

In my case I could fix the issue by simply removing the use of decodeURIComponent() since item.getFilename() already returns a decoded string. But I don't know if it is safe or not to remove this ?

Custom Headers Support

Greetings,
I really like the module and I was wondering if you are willing to add support for custom headers, for use cases such as authorization.
Thank you.

Feature Request: multiple destinations for bulk download

Hi Daniel, I am using your awesome scripts in my current project, an electron app that must download and recreate a file/folder structure from a server.
I am currently struggling with the intricacies of downloading a bunch of files respecting their original position in an existing folder structure: do you plan to add the possibility to set a different download path for each item in the bulkDownload function?
Thanks

Add a 'onProgress' on 'bulkDownload'

I wanted to use a onProgress function but it doesn't exist.

I read the code and saw that all callback are executed (see L166).
I think it is triky to have a percentage easily with this code but I think we can do a onProgress function which will send the number of sucess and error when there is a callback.
It will be usefull for me as I have many items to download from a single server, my users need feedbacks.

If you agree with this feature I can code it for you.

onProgress does not work on Renderer Process.

why onProgress does not work on Renderer Process?

require("electron").remote.require("electron-download-manager").download({
                url: link,
				//path : pathsave,
				onProgress: function (percentage){ 
					console.log("percentage : " + percentage );
				}
            }, function(error, url){
                if(error){
                    alert("ERROR: " + url);
                    return;
                }
 
                alert("DONE: " + url);
 
            }); 

svg base64 - bukdownload

data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIj8+CjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2aWV3Qm94PSIwIDAgNTAgNTAiPgogICAgPHBhdGggc3R5bGU9ImxpbmUtaGVpZ2h0Om5vcm1hbDt0ZXh0LWluZGVudDowO3RleHQtYWxpZ246c3RhcnQ7dGV4dC1kZWNvcmF0aW9uLWxpbmU6bm9uZTt0ZXh0LWRlY29yYXRpb24tc3R5bGU6c29saWQ7dGV4dC1kZWNvcmF0aW9uLWNvbG9yOiMwMDA7dGV4dC10cmFuc2Zvcm06bm9uZTtibG9jay1wcm9ncmVzc2lvbjp0Yjtpc29sYXRpb246YXV0bzttaXgtYmxlbmQtbW9kZTpub3JtYWwiIGQ9Ik0gMTIgMCBDIDEwLjkwNjkzNyAwIDEwIDA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DM1IEwgMzUgMzcgTCAyNiAzNyBMIDI2IDM2IEMgMjYgMzMuODg0IDI3Ljg4ODg0NCAzMi43MTIwNzggMjkuNzE0ODQ0IDMxLjU4MDA3OCBDIDMxLjY5ODg0NCAzMC4zNDkwNzggMzMgMjkuNDM1IDMzIDI4IEMgMzIuOTk5IDI3LjUyMyAzMi44MTE1IDI2IDMwLjQzNzUgMjYgQyAyOC4wNjg1IDI2IDI4IDI3Ljc5NSAyOCAyOCBMIDI2IDI4IEMgMjYgMjYuODg3IDI2Ljc5NzUgMjQgMzAuNDM3NSAyNCB6IiBmb250LXdlaWdodD0iNDAwIiBmb250LWZhbWlseT0ic2Fucy1zZXJpZiIgd2hpdGUtc3BhY2U9Im5vcm1hbCIgb3ZlcmZsb3c9InZpc2libGUiLz4KPC9zdmc+Cg==

"getOwnerBrowserWindow" error when file already exists

image

preload.js

`
async downloadGame({ version, onProgress, onFinish }) {
let timeStarted = new Date();
let downloadLinks = [];
gameDownloadList.map((file) => downloadLinks.push(BASE_URL + file));

ipcRenderer.send("download", {
  downloadLinks,
  directory: path.resolve(),
});

const progressHandler = (
  event,
  { transferredBytes, percent, totalBytes }
) => {
  let timeElapsed = new Date() - timeStarted; // Assuming that timeStarted is a Date Object
  let downloadSpeed = transferredBytes / (timeElapsed / 1000); // Upload speed in second

  if (onProgress) {
    onProgress({
      transferredBytes,
      percent,
      totalBytes,
      downloadSpeed,
      version,
    });
  }
};

const completeHandler = () => {
  ipcRenderer.off("download progress", progressHandler);
  ipcRenderer.off("download complete", completeHandler);
  onFinish();
};

ipcRenderer.on("download progress", progressHandler);
ipcRenderer.on("download complete", completeHandler);

}
`

main.js
`
session.defaultSession.on("will-download", (event, item, webContents) => {
item.on("updated", (event, state) => {
if (state === "interrupted") {
console.log("Download is interrupted but can be resumed");
} else if (state === "progressing") {
if (item.isPaused()) {
console.log("Download is paused");
} else {
if (!downloadInfo.hasOwnProperty(item.getFilename())) {
totalBytes += item.getTotalBytes();
}
downloadInfo[item.getFilename()] = {
totalBytes: item.getTotalBytes(),
downloadedBytes: item.getReceivedBytes(),
};
}
}

  totalReceivedBytes = Object.entries(downloadInfo)
    .map((el) => el[1]["downloadedBytes"])
    .reduce((prev, next) => prev + next);

  //transferredBytes, percent, totalBytes;

  mainWindow.webContents.send("download progress", {
    totalBytes,
    transferredBytes: totalReceivedBytes,
    percent: totalReceivedBytes / totalBytes,
  });
});

ipcMain.on("cancel", () => {
  item.cancel();
});

});
`

Feature request

When downloading a single file it would be really nice if I could rename in the download process.

Perhaps a filename param in the options

Using onProgress for items in bulkDownload

I'd like to use the bulkDownload option to download an array of up to 10 links, all of which are presented to the user in the form of a "card", showing name, size and a manual download-button.
Up until now everything works, had to make som minor adjustments to get a custom, dynamic path to work (or maybe I didn't check the documentations too well).

The only exception is that I'd really like to show the progress of all the downloads on the cards, and I can't seem to figure out how to do this. I'm fairly new to node but it looks like the bulkDownload makes use of the normal download function, and thus there might be a possibility for this to work?

Here's the relevant code from my config

window.download = function (links, elements) {
    var dlPath = document.getElementById('dl-path').innerText;

    DownloadManager.bulkDownload({
        urls: links,
        downloadFolder: dlPath + "/ZU_Downloads",
        onProgress: (progress, item) => {
            console.log(progress);
            console.log(item.getFilename())
            console.log(item.getTotalBytes())
        }

    }, function (error, finished, errors) {
        if (error) {
            console.log("finished: " + finished);
            console.log("errors: " + errors);
            return;
        }

        console.log("all finished", finished);
        // Make buttons green when done
        for (let element of elements) {
            element.children[0].style = "background:#5d9c7d!important;transition:.2s;"
            element.children[1].style = "background:#5d9c7d!important;transition:.2s;"
        }
    })
}

bulkDownload callback not fired sometimes

the bulkDownload downloads all files of my array,
but it is not triggering the callback, the function body is completly ignored sometimes

const dl = app.require("electron-download-manager")

function downloadSiteColorURLFILELinksFiles() {
  const siteColorURLFILELinksFilesFromList = $(
    "#chooseColors ul .isURLfromURLFILE"
  );
  let siteColorURLFILELinksFiles = [];

  siteColorURLFILELinksFilesFromList.each(function() {
    siteColorURLFILELinksFiles.push($(this).html());
  });

  console.log(siteColorURLFILELinksFiles);
  console.log("downloading now all files from list");

  dl.bulkDownload(
    {
      urls: siteColorURLFILELinksFiles,
      path: ``
    },
    function(error, finished, errors) {
      if (error) {
        console.log("finished: " + finished);
        console.log("error: " + error);
        console.log("errors: " + errors);
      }
      console.log("all files downloaded");

      colorFileList.append(
        "<li class='li-seperator'>" + "downloaded files are:" + "</li>"
      );

      const siteColorURLFILElinksFilesDownloaded = fs.readdirSync(
        __dirname + colorSiteDownloadDIR,
        "utf8"
      );
      siteColorURLFILElinksFilesDownloaded.forEach(file => {
        colorFileList.append(
          "<li class='isFILE'>" +
            __dirname +
            colorSiteDownloadDIR +
            file +
            "</li>"
        );
      });
    }
  );
  console.log("after dl.bulkDownload function")
  siteColorURLFILELinksFiles = []
}

the console.log("finished/error etc") is not fired, also the console.log("all files downloaded) is not fired, but all files are downloaded, i see all in the download folder.
electron-download-manager just doesn't know when all files are downloaded sometimes.

well, it actually happes randomly, doesnt matter if the files exist before or not ...
any idea?

// i wanna add all downloaded files to a ul to read them later with the fs module

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.