FileDownloader.js 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  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, opts, callback, abort) {
  10. let errMes = '';
  11. let 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. if (opts)
  22. options = Object.assign({}, opts, options);
  23. try {
  24. const res = await axios.get(url, options);
  25. let estSize = 0;
  26. if (res.headers['content-length']) {
  27. estSize = res.headers['content-length'];
  28. }
  29. if (this.limitDownloadSize && estSize > this.limitDownloadSize) {
  30. throw new Error('Файл слишком большой');
  31. }
  32. let prevProg = 0;
  33. let transferred = 0;
  34. const download = this.streamToBuffer(res.data, (chunk) => {
  35. transferred += chunk.length;
  36. if (this.limitDownloadSize) {
  37. if (transferred > this.limitDownloadSize) {
  38. errMes = 'Файл слишком большой';
  39. res.request.abort();
  40. }
  41. }
  42. let prog = 0;
  43. if (estSize)
  44. prog = Math.round(transferred/estSize*100);
  45. else
  46. prog = Math.round(transferred/(transferred + 200000)*100);
  47. if (prog != prevProg && callback)
  48. callback(prog);
  49. prevProg = prog;
  50. if (abort && abort()) {
  51. errMes = 'abort';
  52. res.request.abort();
  53. }
  54. });
  55. return await download;
  56. } catch (error) {
  57. errMes = (errMes ? errMes : error.message);
  58. throw new Error(errMes);
  59. }
  60. }
  61. async head(url) {
  62. const options = {
  63. headers: {
  64. 'user-agent': userAgent,
  65. timeout: 10*1000,
  66. },
  67. };
  68. const res = await axios.head(url, options);
  69. return res.headers;
  70. }
  71. streamToBuffer(stream, progress, timeout = 30*1000) {
  72. return new Promise((resolve, reject) => {
  73. if (!progress)
  74. progress = () => {};
  75. const _buf = [];
  76. let resolved = false;
  77. let timer = 0;
  78. stream.on('data', (chunk) => {
  79. timer = 0;
  80. _buf.push(chunk);
  81. progress(chunk);
  82. });
  83. stream.on('end', () => {
  84. resolved = true;
  85. timer = timeout;
  86. resolve(Buffer.concat(_buf));
  87. });
  88. stream.on('error', (err) => {
  89. reject(err);
  90. });
  91. stream.on('aborted', () => {
  92. reject(new Error('aborted'));
  93. });
  94. //бодяга с timer и timeout, чтобы гарантировать отсутствие зависания по каким-либо причинам
  95. (async() => {
  96. while (timer < timeout) {
  97. await utils.sleep(1000);
  98. timer += 1000;
  99. }
  100. if (!resolved)
  101. reject(new Error('FileDownloader: timed out'))
  102. })();
  103. });
  104. }
  105. }
  106. module.exports = FileDownloader;