ConvertBase.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. const fs = require('fs-extra');
  2. const iconv = require('iconv-lite');
  3. const chardet = require('chardet');
  4. const he = require('he');
  5. const LimitedQueue = require('../../LimitedQueue');
  6. const textUtils = require('./textUtils');
  7. const utils = require('../../utils');
  8. const queue = new LimitedQueue(2, 20, 3*60*1000);//3 минуты ожидание подвижек
  9. class ConvertBase {
  10. constructor(config) {
  11. this.config = config;
  12. this.calibrePath = `${config.dataDir}/calibre/ebook-convert`;
  13. this.sofficePath = '/usr/bin/soffice';
  14. this.pdfToHtmlPath = '/usr/bin/pdftohtml';
  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. }
  27. async execConverter(path, args, onData, abort) {
  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: 600,
  37. args,
  38. onData: (data) => {
  39. q.resetTimeout();
  40. onData(data);
  41. },
  42. abort
  43. });
  44. if (result.code != 0) {
  45. let error = result.code;
  46. if (this.config.branch == 'development')
  47. error = `exec: ${path}, stdout: ${result.stdout}, stderr: ${result.stderr}`;
  48. throw new Error(`Внешний конвертер завершился с ошибкой: ${error}`);
  49. }
  50. } catch(e) {
  51. if (e.status == 'killed') {
  52. throw new Error('Слишком долгое ожидание конвертера');
  53. } else if (e.status == 'abort') {
  54. throw new Error('abort');
  55. } else if (e.status == 'error') {
  56. throw new Error(e.error);
  57. } else {
  58. throw new Error(e);
  59. }
  60. } finally {
  61. q.ret();
  62. }
  63. }
  64. decode(data) {
  65. let selected = textUtils.getEncoding(data);
  66. if (selected == 'ISO-8859-5') {
  67. const charsetAll = chardet.detectAll(data.slice(0, 20000));
  68. for (const charset of charsetAll) {
  69. if (charset.name.indexOf('ISO-8859') < 0) {
  70. selected = charset.name;
  71. break;
  72. }
  73. }
  74. }
  75. if (selected.toLowerCase() != 'utf-8')
  76. return iconv.decode(data, selected);
  77. else
  78. return data;
  79. }
  80. repSpaces(text) {
  81. return text.replace(/&nbsp;|[\t\n\r]/g, ' ');
  82. }
  83. escapeEntities(text) {
  84. return he.escape(he.decode(text.replace(/&nbsp;/g, ' ')));
  85. }
  86. formatFb2(fb2) {
  87. let out = '<?xml version="1.0" encoding="utf-8"?>';
  88. out += '<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">';
  89. out += this.formatFb2Node(fb2);
  90. out += '</FictionBook>';
  91. return out;
  92. }
  93. formatFb2Node(node, name) {
  94. let out = '';
  95. if (Array.isArray(node)) {
  96. for (const n of node) {
  97. out += this.formatFb2Node(n);
  98. }
  99. } else if (typeof node == 'string') {
  100. if (name)
  101. out += `<${name}>${this.repSpaces(node)}</${name}>`;
  102. else
  103. out += this.repSpaces(node);
  104. } else {
  105. if (node._n)
  106. name = node._n;
  107. let attrs = '';
  108. if (node._attrs) {
  109. for (let attrName in node._attrs) {
  110. attrs += ` ${attrName}="${node._attrs[attrName]}"`;
  111. }
  112. }
  113. let tOpen = '';
  114. let tBody = '';
  115. let tClose = '';
  116. if (name)
  117. tOpen += `<${name}${attrs}>`;
  118. if (node.hasOwnProperty('_t'))
  119. tBody += this.repSpaces(node._t);
  120. for (let nodeName in node) {
  121. if (nodeName && nodeName[0] == '_' && nodeName != '_a')
  122. continue;
  123. const n = node[nodeName];
  124. tBody += this.formatFb2Node(n, nodeName);
  125. }
  126. if (name)
  127. tClose += `</${name}>`;
  128. if (attrs == '' && name == 'p' && tBody.trim() == '')
  129. out += '<empty-line/>'
  130. else
  131. out += `${tOpen}${tBody}${tClose}`;
  132. }
  133. return out;
  134. }
  135. }
  136. module.exports = ConvertBase;