ConvertBase.js 5.3 KB

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