ConvertBase.js 5.1 KB

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