ConvertBase.js 5.1 KB

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