ConvertJpegPng.js 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. const fs = require('fs-extra');
  2. const path = require('path');
  3. //const utils = require('../../utils');
  4. const ConvertBase = require('./ConvertBase');
  5. class ConvertJpegPng extends ConvertBase {
  6. check(data, opts) {
  7. const {inputFiles} = opts;
  8. return this.config.useExternalBookConverter &&
  9. inputFiles.sourceFileType &&
  10. (inputFiles.sourceFileType.ext == 'jpg' || inputFiles.sourceFileType.ext == 'png' );
  11. }
  12. async run(data, opts) {
  13. const {inputFiles, uploadFileName, imageFiles} = opts;
  14. if (!imageFiles) {
  15. if (!this.check(data, opts))
  16. return false;
  17. }
  18. let files = [];
  19. if (imageFiles) {
  20. files = imageFiles;
  21. } else {
  22. const imageFile = `${inputFiles.filesDir}/${path.basename(inputFiles.sourceFile)}.${inputFiles.sourceFileType.ext}`;
  23. await fs.copy(inputFiles.sourceFile, imageFile);
  24. files.push({src: imageFile});
  25. }
  26. //читаем изображения
  27. const limitSize = 2*this.config.maxUploadFileSize;
  28. let imagesSize = 0;
  29. const loadImage = async(image) => {
  30. const src = path.parse(image.src);
  31. let type = 'unknown';
  32. switch (src.ext) {
  33. case '.jpg': type = 'image/jpeg'; break;
  34. case '.png': type = 'image/png'; break;
  35. }
  36. if (type != 'unknown') {
  37. image.data = (await fs.readFile(image.src)).toString('base64');
  38. image.type = type;
  39. image.name = src.base;
  40. imagesSize += image.data.length;
  41. if (imagesSize > limitSize) {
  42. throw new Error(`Файл для конвертирования слишком большой|FORLOG| imagesSize: ${imagesSize} > ${limitSize}`);
  43. }
  44. }
  45. }
  46. let images = [];
  47. let loading = [];
  48. files.forEach(img => {
  49. images.push(img);
  50. loading.push(loadImage(img));
  51. });
  52. await Promise.all(loading);
  53. //формируем fb2
  54. let titleInfo = {};
  55. let desc = {_n: 'description', 'title-info': titleInfo};
  56. let pars = [];
  57. let body = {_n: 'body', section: {_a: [pars]}};
  58. let binary = [];
  59. let fb2 = [desc, body, binary];
  60. let title = '';
  61. if (uploadFileName)
  62. title = uploadFileName;
  63. titleInfo['book-title'] = title;
  64. for (const image of images) {
  65. if (image.type) {
  66. const img = {_n: 'binary', _attrs: {id: image.name, 'content-type': image.type}, _t: image.data};
  67. binary.push(img);
  68. const attrs = {'l:href': `#${image.name}`};
  69. if (image.alt)
  70. attrs.alt = image.alt;
  71. pars.push({_n: 'p', _t: ''});
  72. pars.push({_n: 'image', _attrs: attrs});
  73. }
  74. }
  75. pars.push({_n: 'p', _t: ''});
  76. return this.formatFb2(fb2);
  77. }
  78. }
  79. module.exports = ConvertJpegPng;