ConvertBase.js 4.5 KB

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