prepareBinaries.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. "use strict";
  2. const request = require("request");
  3. const decompress = require("decompress");
  4. const fs = require("fs");
  5. const EventEmitter = require("events").EventEmitter;
  6. const url = require('url');
  7. function isBinaryFileRequired(flashSpecification, fileName) {
  8. return flashSpecification.map(binary => binary.path).indexOf(fileName) !== -1;
  9. }
  10. function addBufferToBinary(flashSpecification, fileName, buffer) {
  11. flashSpecification.forEach((element, index) => {
  12. if (flashSpecification[index].path === fileName) {
  13. flashSpecification[index].buffer = buffer;
  14. }
  15. });
  16. }
  17. function prepareBinaries(manifest) {
  18. const eventEmitter = new EventEmitter();
  19. const flashContents = manifest.flash;
  20. let body;
  21. let contentLength;
  22. const pathName = url.parse(manifest.download).pathname;
  23. const fileName = pathName.split("/").pop();
  24. request(manifest.download)
  25. .on("response", response => {
  26. contentLength = Number(response.headers["content-length"]);
  27. })
  28. .on("data", data => {
  29. if (body) {
  30. body = Buffer.concat([body, data]);
  31. } else {
  32. body = data;
  33. }
  34. const progress = {
  35. details: {
  36. downloadedBytes: body.length,
  37. downloadSize: contentLength
  38. },
  39. display: "Downloading"
  40. };
  41. eventEmitter.emit("progress", progress);
  42. })
  43. .on("complete", () => {
  44. let preparedPromise;
  45. if (manifest.download.toLowerCase().endsWith(".zip")) {
  46. preparedPromise = decompress(body, {
  47. filter: file => isBinaryFileRequired(flashContents, file.path)
  48. })
  49. .then(files => {
  50. files.forEach(
  51. file => addBufferToBinary(flashContents, file.path, file.data)
  52. );
  53. });
  54. } else {
  55. preparedPromise = new Promise((resolve, reject) => {
  56. addBufferToBinary(flashContents, fileName, body);
  57. resolve();
  58. });
  59. }
  60. preparedPromise.then(() => eventEmitter.emit("complete", flashContents))
  61. .catch(err => eventEmitter.emit("error", err));
  62. })
  63. .on("error", err => eventEmitter.emit("error", err));
  64. return eventEmitter;
  65. }
  66. module.exports = prepareBinaries;