ConvertBase.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. const fs = require('fs-extra');
  2. const iconv = require('iconv-lite');
  3. const he = require('he');
  4. const LimitedQueue = require('../../LimitedQueue');
  5. const textUtils = require('./textUtils');
  6. const utils = require('../../utils');
  7. const queue = new LimitedQueue(2, 20, 3*60*1000);//3 минуты ожидание подвижек
  8. class ConvertBase {
  9. constructor(config) {
  10. this.config = config;
  11. this.calibrePath = `${config.dataDir}/calibre/ebook-convert`;
  12. this.sofficePath = '/usr/bin/soffice';
  13. this.pdfToHtmlPath = '/usr/bin/pdftohtml';
  14. }
  15. async run(data, opts) {// eslint-disable-line no-unused-vars
  16. //override
  17. }
  18. async checkExternalConverterPresent() {
  19. if (!await fs.pathExists(this.calibrePath))
  20. throw new Error('Внешний конвертер calibre не найден');
  21. if (!await fs.pathExists(this.sofficePath))
  22. throw new Error('Внешний конвертер LibreOffice не найден');
  23. if (!await fs.pathExists(this.pdfToHtmlPath))
  24. throw new Error('Внешний конвертер pdftohtml не найден');
  25. }
  26. async execConverter(path, args, onData, abort) {
  27. onData = (onData ? onData : () => {});
  28. let q = null;
  29. try {
  30. q = await queue.get(() => {onData();});
  31. } catch (e) {
  32. throw new Error('Слишком большая очередь конвертирования. Пожалуйста, попробуйте позже.');
  33. }
  34. try {
  35. const result = await utils.spawnProcess(path, {
  36. killAfter: 600,
  37. args,
  38. onData: (data) => {
  39. q.resetTimeout();
  40. onData(data);
  41. },
  42. abort
  43. });
  44. if (result.code != 0) {
  45. let error = result.code;
  46. if (this.config.branch == 'development')
  47. error = `exec: ${path}, stdout: ${result.stdout}, stderr: ${result.stderr}`;
  48. throw new Error(`Внешний конвертер завершился с ошибкой: ${error}`);
  49. }
  50. } catch(e) {
  51. if (e.status == 'killed') {
  52. throw new Error('Слишком долгое ожидание конвертера');
  53. } else if (e.status == 'abort') {
  54. throw new Error('abort');
  55. } else if (e.status == 'error') {
  56. throw new Error(e.error);
  57. } else {
  58. throw new Error(e);
  59. }
  60. } finally {
  61. q.ret();
  62. }
  63. }
  64. decode(data) {
  65. let selected = textUtils.getEncoding(data);
  66. if (selected.toLowerCase() != 'utf-8')
  67. return iconv.decode(data, selected);
  68. else
  69. return data;
  70. }
  71. repSpaces(text) {
  72. return text.replace(/ |[\t\n\r]/g, ' ');
  73. }
  74. escapeEntities(text) {
  75. return he.escape(he.decode(text.replace(/ /g, ' ')));
  76. }
  77. formatFb2(fb2) {
  78. let out = '<?xml version="1.0" encoding="utf-8"?>';
  79. out += '<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">';
  80. out += this.formatFb2Node(fb2);
  81. out += '</FictionBook>';
  82. return out;
  83. }
  84. formatFb2Node(node, name) {
  85. let out = '';
  86. if (Array.isArray(node)) {
  87. for (const n of node) {
  88. out += this.formatFb2Node(n);
  89. }
  90. } else if (typeof node == 'string') {
  91. if (name)
  92. out += `<${name}>${this.repSpaces(node)}</${name}>`;
  93. else
  94. out += this.repSpaces(node);
  95. } else {
  96. if (node._n)
  97. name = node._n;
  98. let attrs = '';
  99. if (node._attrs) {
  100. for (let attrName in node._attrs) {
  101. attrs += ` ${attrName}="${node._attrs[attrName]}"`;
  102. }
  103. }
  104. let tOpen = '';
  105. let tBody = '';
  106. let tClose = '';
  107. if (name)
  108. tOpen += `<${name}${attrs}>`;
  109. if (node.hasOwnProperty('_t'))
  110. tBody += this.repSpaces(node._t);
  111. for (let nodeName in node) {
  112. if (nodeName && nodeName[0] == '_' && nodeName != '_a')
  113. continue;
  114. const n = node[nodeName];
  115. tBody += this.formatFb2Node(n, nodeName);
  116. }
  117. if (name)
  118. tClose += `</${name}>`;
  119. if (attrs == '' && name == 'p' && tBody.trim() == '')
  120. out += '<empty-line/>'
  121. else
  122. out += `${tOpen}${tBody}${tClose}`;
  123. }
  124. return out;
  125. }
  126. }
  127. module.exports = ConvertBase;