ConvertBase.js 5.3 KB

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