FileDownloader.js 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. const https = require('https');
  2. const axios = require('axios');
  3. const utils = require('./utils');
  4. const userAgent = 'Mozilla/5.0 (X11; HasCodingOs 1.0; Linux x64) AppleWebKit/637.36 (KHTML, like Gecko) Chrome/70.0.3112.101 Safari/637.36 HasBrowser/5.0';
  5. class FileDownloader {
  6. constructor(limitDownloadSize = 0) {
  7. this.limitDownloadSize = limitDownloadSize;
  8. }
  9. async load(url, callback, abort) {
  10. let errMes = '';
  11. const options = {
  12. headers: {
  13. 'user-agent': userAgent,
  14. timeout: 300*1000,
  15. },
  16. httpsAgent: new https.Agent({
  17. rejectUnauthorized: false // решение проблемы 'unable to verify the first certificate' для некоторых сайтов с валидным сертификатом
  18. }),
  19. responseType: 'stream',
  20. };
  21. try {
  22. const res = await axios.get(url, options);
  23. let estSize = 0;
  24. if (res.headers['content-length']) {
  25. estSize = res.headers['content-length'];
  26. }
  27. if (this.limitDownloadSize && estSize > this.limitDownloadSize) {
  28. throw new Error('Файл слишком большой');
  29. }
  30. let prevProg = 0;
  31. let transferred = 0;
  32. const download = this.streamToBuffer(res.data, (chunk) => {
  33. transferred += chunk.length;
  34. if (this.limitDownloadSize) {
  35. if (transferred > this.limitDownloadSize) {
  36. errMes = 'Файл слишком большой';
  37. res.request.abort();
  38. }
  39. }
  40. let prog = 0;
  41. if (estSize)
  42. prog = Math.round(transferred/estSize*100);
  43. else
  44. prog = Math.round(transferred/(transferred + 200000)*100);
  45. if (prog != prevProg && callback)
  46. callback(prog);
  47. prevProg = prog;
  48. if (abort && abort()) {
  49. errMes = 'abort';
  50. res.request.abort();
  51. }
  52. });
  53. return await download;
  54. } catch (error) {
  55. errMes = (errMes ? errMes : error.message);
  56. throw new Error(errMes);
  57. }
  58. }
  59. async head(url) {
  60. const options = {
  61. headers: {
  62. 'user-agent': userAgent,
  63. timeout: 10*1000,
  64. },
  65. };
  66. const res = await axios.head(url, options);
  67. return res.headers;
  68. }
  69. streamToBuffer(stream, progress, timeout = 30*1000) {
  70. return new Promise((resolve, reject) => {
  71. if (!progress)
  72. progress = () => {};
  73. const _buf = [];
  74. let resolved = false;
  75. let timer = 0;
  76. stream.on('data', (chunk) => {
  77. timer = 0;
  78. _buf.push(chunk);
  79. progress(chunk);
  80. });
  81. stream.on('end', () => {
  82. resolved = true;
  83. timer = timeout;
  84. resolve(Buffer.concat(_buf));
  85. });
  86. stream.on('error', (err) => {
  87. reject(err);
  88. });
  89. stream.on('aborted', () => {
  90. reject(new Error('aborted'));
  91. });
  92. //бодяга с timer и timeout, чтобы гарантировать отсутствие зависания по каким-либо причинам
  93. (async() => {
  94. while (timer < timeout) {
  95. await utils.sleep(1000);
  96. timer += 1000;
  97. }
  98. if (!resolved)
  99. reject(new Error('FileDownloader: timed out'))
  100. })();
  101. });
  102. }
  103. }
  104. module.exports = FileDownloader;