ConvertBase.js 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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. const error = `${result.code}|FORLOG|, exec: ${path}, args: ${args.join(' ')}, stdout: ${result.stdout}, stderr: ${result.stderr}`;
  46. throw new Error(`Внешний конвертер завершился с ошибкой: ${error}`);
  47. }
  48. } catch(e) {
  49. if (e.status == 'killed') {
  50. throw new Error('Слишком долгое ожидание конвертера');
  51. } else if (e.status == 'abort') {
  52. throw new Error('abort');
  53. } else if (e.status == 'error') {
  54. throw new Error(e.error);
  55. } else {
  56. throw new Error(e);
  57. }
  58. } finally {
  59. q.ret();
  60. }
  61. }
  62. decode(data) {
  63. let selected = textUtils.getEncoding(data);
  64. if (selected.toLowerCase() != 'utf-8')
  65. return iconv.decode(data, selected);
  66. else
  67. return data;
  68. }
  69. repSpaces(text) {
  70. return text.replace(/ |[\t\n\r]/g, ' ');
  71. }
  72. escapeEntities(text) {
  73. return he.escape(he.decode(text.replace(/ /g, ' ')));
  74. }
  75. formatFb2(fb2) {
  76. let out = '<?xml version="1.0" encoding="utf-8"?>';
  77. out += '<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">';
  78. out += this.formatFb2Node(fb2);
  79. out += '</FictionBook>';
  80. return out;
  81. }
  82. formatFb2Node(node, name) {
  83. let out = '';
  84. if (Array.isArray(node)) {
  85. for (const n of node) {
  86. out += this.formatFb2Node(n);
  87. }
  88. } else if (typeof node == 'string') {
  89. if (name)
  90. out += `<${name}>${this.repSpaces(node)}</${name}>`;
  91. else
  92. out += this.repSpaces(node);
  93. } else {
  94. if (node._n)
  95. name = node._n;
  96. let attrs = '';
  97. if (node._attrs) {
  98. for (let attrName in node._attrs) {
  99. attrs += ` ${attrName}="${node._attrs[attrName]}"`;
  100. }
  101. }
  102. let tOpen = '';
  103. let tBody = '';
  104. let tClose = '';
  105. if (name)
  106. tOpen += `<${name}${attrs}>`;
  107. if (node.hasOwnProperty('_t'))
  108. tBody += this.repSpaces(node._t);
  109. for (let nodeName in node) {
  110. if (nodeName && nodeName[0] == '_' && nodeName != '_a')
  111. continue;
  112. const n = node[nodeName];
  113. tBody += this.formatFb2Node(n, nodeName);
  114. }
  115. if (name)
  116. tClose += `</${name}>`;
  117. if (attrs == '' && name == 'p' && tBody.trim() == '')
  118. out += '<empty-line/>'
  119. else
  120. out += `${tOpen}${tBody}${tClose}`;
  121. }
  122. return out;
  123. }
  124. }
  125. module.exports = ConvertBase;