ConvertBase.js 5.2 KB

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