ConvertFb3.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. const fs = require('fs-extra');
  2. const ConvertHtml = require('./ConvertHtml');
  3. class ConvertDocX extends ConvertHtml {
  4. async check(data, opts) {
  5. const {inputFiles} = opts;
  6. if (this.config.useExternalBookConverter &&
  7. inputFiles.sourceFileType && inputFiles.sourceFileType.ext == 'zip') {
  8. //ищем файл '[Content_Types].xml'
  9. for (const file of inputFiles.files) {
  10. if (file.path == '[Content_Types].xml') {
  11. const contentTypes = await fs.readFile(`${inputFiles.filesDir}/${file.path}`, 'utf8');
  12. return contentTypes.indexOf('/fb3/body.xml') >= 0;
  13. }
  14. }
  15. }
  16. return false;
  17. }
  18. getTitle(text) {
  19. let title = '';
  20. const m = text.match(/<title>([\s\S]*?)<\/title>/);
  21. if (m)
  22. title = m[1];
  23. return title.trim();
  24. }
  25. async run(data, opts) {
  26. if (!(await this.check(data, opts)))
  27. return false;
  28. const {inputFiles} = opts;
  29. let text = await fs.readFile(`${inputFiles.filesDir}/fb3/body.xml`, 'utf8');
  30. const title = this.getTitle(text)
  31. .replace(/<\/?p>/g, '')
  32. ;
  33. text = `<title>${title}</title>` + text
  34. .replace(/<title>/g, '<br><b>')
  35. .replace(/<\/title>/g, '</b><br>')
  36. .replace(/<subtitle>/g, '<br><br><subtitle>')
  37. ;
  38. return await super.run(Buffer.from(text), {skipCheck: true, cutTitle: true});
  39. }
  40. }
  41. module.exports = ConvertDocX;