ConvertBase.js 4.7 KB

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