ConvertDjvu.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. const fs = require('fs-extra');
  2. const path = require('path');
  3. const utils = require('../../utils');
  4. const ConvertJpegPng = require('./ConvertJpegPng');
  5. class ConvertDjvu extends ConvertJpegPng {
  6. check(data, opts) {
  7. const {inputFiles} = opts;
  8. return this.config.useExternalBookConverter &&
  9. inputFiles.sourceFileType && inputFiles.sourceFileType.ext == 'djvu';
  10. }
  11. async run(data, opts) {
  12. if (!this.check(data, opts))
  13. return false;
  14. const {inputFiles, callback, abort} = opts;
  15. const ddjvuPath = '/usr/bin/ddjvu';
  16. if (!await fs.pathExists(ddjvuPath))
  17. throw new Error('Внешний конвертер ddjvu не найден');
  18. const tiffsplitPath = '/usr/bin/tiffsplit';
  19. if (!await fs.pathExists(tiffsplitPath))
  20. throw new Error('Внешний конвертер tiffsplitPath не найден');
  21. const mogrifyPath = '/usr/bin/mogrify';
  22. if (!await fs.pathExists(mogrifyPath))
  23. throw new Error('Внешний конвертер mogrifyPath не найден');
  24. const dir = `${inputFiles.filesDir}/`;
  25. const baseFile = `${dir}${path.basename(inputFiles.sourceFile)}`;
  26. const tifFile = `${baseFile}.tif`;
  27. //конвертируем в tiff
  28. let perc = 0;
  29. await this.execConverter(ddjvuPath, ['-format=tiff', '-quality=50', '-verbose', inputFiles.sourceFile, tifFile], () => {
  30. perc = (perc < 100 ? perc + 1 : 40);
  31. callback(perc);
  32. }, abort);
  33. const tifFileSize = (await fs.stat(tifFile)).size;
  34. let limitSize = 4*this.config.maxUploadFileSize;
  35. if (tifFileSize > limitSize) {
  36. throw new Error(`Файл для конвертирования слишком большой|FORLOG| tifFileSize: ${tifFileSize} > ${limitSize}`);
  37. }
  38. //разбиваем на файлы
  39. await this.execConverter(tiffsplitPath, [tifFile, dir], null, abort);
  40. await fs.remove(tifFile);
  41. //конвертируем в jpg
  42. await this.execConverter(mogrifyPath, ['-quality', '20', '-scale', '2048>', '-verbose', '-format', 'jpg', `${dir}*.tif`], () => {
  43. perc = (perc < 100 ? perc + 1 : 40);
  44. callback(perc);
  45. }, abort);
  46. //ищем изображения
  47. let files = [];
  48. await utils.findFiles(async(file) => {
  49. if (path.extname(file) == '.jpg')
  50. files.push({name: file, base: path.basename(file)});
  51. }, dir);
  52. files.sort((a, b) => a.base.localeCompare(b.base));
  53. await utils.sleep(100);
  54. return await super.run(data, Object.assign({}, opts, {imageFiles: files.map(f => f.name)}));
  55. }
  56. }
  57. module.exports = ConvertDjvu;