ConvertHtml.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. const ConvertBase = require('./ConvertBase');
  2. const sax = require('./sax');
  3. const textUtils = require('./textUtils');
  4. class ConvertHtml extends ConvertBase {
  5. check(data, opts) {
  6. const {dataType} = opts;
  7. if (dataType && (dataType.ext == 'html' || dataType.ext == 'xml'))
  8. return {isText: false};
  9. //может это чистый текст?
  10. if (textUtils.checkIfText(data)) {
  11. return {isText: true};
  12. }
  13. return false;
  14. }
  15. async run(data, opts) {
  16. let isText = false;
  17. if (!opts.skipCheck) {
  18. const checkResult = this.check(data, opts);
  19. if (!checkResult)
  20. return false;
  21. isText = checkResult.isText;
  22. } else {
  23. isText = opts.isText;
  24. }
  25. const {cutTitle} = opts;
  26. let titleInfo = {};
  27. let desc = {_n: 'description', 'title-info': titleInfo};
  28. let pars = [];
  29. let body = {_n: 'body', section: {_a: []}};
  30. let binary = [];
  31. let fb2 = [desc, body, binary];
  32. let title = '';
  33. let inTitle = false;
  34. let inImage = false;
  35. let image = {};
  36. let bold = false;
  37. let italic = false;
  38. let spaceCounter = [];
  39. const repCrLfTab = (text) => text.replace(/[\n\r]/g, '').replace(/\t/g, ' ');
  40. const newParagraph = () => {
  41. pars.push({_n: 'p', _t: ''});
  42. };
  43. const growParagraph = (text) => {
  44. if (!pars.length)
  45. newParagraph();
  46. const l = pars.length;
  47. pars[l - 1]._t += text;
  48. //посчитаем отступы у текста, чтобы выделить потом параграфы
  49. const lines = text.split('\n');
  50. for (let line of lines) {
  51. if (line.trim() == '')
  52. continue;
  53. line = repCrLfTab(line);
  54. let l = 0;
  55. while (l < line.length && line[l] == ' ') {
  56. l++;
  57. }
  58. if (!spaceCounter[l])
  59. spaceCounter[l] = 0;
  60. spaceCounter[l]++;
  61. }
  62. };
  63. const newPara = new Set(['tr', '/table', 'hr', 'br', 'br/', 'li', 'dt', 'dd', 'p', 'title', '/title', 'h1', 'h2', 'h3', '/h1', '/h2', '/h3']);
  64. const onTextNode = (text, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  65. if (!cutCounter && !(cutTitle && inTitle)) {
  66. let tOpen = (bold ? '<strong>' : '');
  67. tOpen += (italic ? '<emphasis>' : '');
  68. let tClose = (italic ? '</emphasis>' : '');
  69. tClose += (bold ? '</strong>' : '');
  70. growParagraph(`${tOpen}${text}${tClose}`);
  71. }
  72. if (inTitle && !title)
  73. title = text;
  74. if (inImage) {
  75. image._t = text;
  76. binary.push(image);
  77. pars.push({_n: 'image', _attrs: {'l:href': '#' + image._attrs.id}, _t: ''});
  78. newParagraph();
  79. }
  80. };
  81. const onStartNode = (tag, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  82. if (!cutCounter) {
  83. if (newPara.has(tag))
  84. newParagraph();
  85. switch (tag) {
  86. case 'i':
  87. case 'em':
  88. italic = true;
  89. break;
  90. case 'b':
  91. case 'strong':
  92. case 'h1':
  93. case 'h2':
  94. case 'h3':
  95. bold = true;
  96. break;
  97. }
  98. }
  99. if (tag == 'title')
  100. inTitle = true;
  101. if (tag == 'fb2-image') {
  102. inImage = true;
  103. const attrs = sax.getAttrsSync(tail);
  104. image = {_n: 'binary', _attrs: {id: attrs.name.value, 'content-type': attrs.type.value}, _t: ''};
  105. }
  106. };
  107. const onEndNode = (tag, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  108. if (!cutCounter) {
  109. if (newPara.has('/' + tag))
  110. newParagraph();
  111. switch (tag) {
  112. case 'i':
  113. case 'em':
  114. italic = false;
  115. break;
  116. case 'b':
  117. case 'strong':
  118. case 'h1':
  119. case 'h2':
  120. case 'h3':
  121. bold = false;
  122. break;
  123. }
  124. }
  125. if (tag == 'title')
  126. inTitle = false;
  127. if (tag == 'fb2-image')
  128. inImage = false;
  129. };
  130. let buf = this.decode(data).toString();
  131. sax.parseSync(buf, {
  132. onStartNode, onEndNode, onTextNode,
  133. innerCut: new Set(['head', 'script', 'style', 'binary', 'fb2-image'])
  134. });
  135. titleInfo['book-title'] = title;
  136. //подозрение на чистый текст, надо разбить на параграфы
  137. if (isText || pars.length < buf.length/2000) {
  138. let total = 0;
  139. let count = 1;
  140. for (let i = 0; i < spaceCounter.length; i++) {
  141. const sc = (spaceCounter[i] ? spaceCounter[i] : 0);
  142. if (sc) count++;
  143. total += sc;
  144. }
  145. let d = 0;
  146. const mid = total/count;
  147. for (let i = 0; i < spaceCounter.length; i++) {
  148. const sc = (spaceCounter[i] ? spaceCounter[i] : 0);
  149. if (sc > mid) d++;
  150. }
  151. let i = 0;
  152. //если разброс не слишком большой, выделяем параграфы
  153. if (d < 10 && spaceCounter.length) {
  154. total /= 20;
  155. i = spaceCounter.length - 1;
  156. while (i > 0 && (!spaceCounter[i] || spaceCounter[i] < total)) i--;
  157. }
  158. const parIndent = (i > 0 ? i : 0);
  159. let newPars = [];
  160. const newPar = () => {
  161. newPars.push({_n: 'p', _t: ''});
  162. };
  163. const growPar = (text) => {
  164. if (!newPars.length)
  165. newPar();
  166. const l = newPars.length;
  167. newPars[l - 1]._t += text;
  168. }
  169. i = 0;
  170. for (const par of pars) {
  171. if (par._n != 'p') {
  172. newPars.push(par);
  173. continue;
  174. }
  175. if (i > 0)
  176. newPar();
  177. i++;
  178. let j = 0;
  179. const lines = par._t.split('\n');
  180. for (let line of lines) {
  181. line = repCrLfTab(line);
  182. let l = 0;
  183. while (l < line.length && line[l] == ' ') {
  184. l++;
  185. }
  186. if (l >= parIndent) {
  187. if (j > 0)
  188. newPar();
  189. j++;
  190. }
  191. growPar(line.trim() + ' ');
  192. }
  193. }
  194. body.section._a[0] = newPars;
  195. } else {
  196. body.section._a[0] = pars;
  197. }
  198. //убираем лишнее
  199. pars = body.section._a[0];
  200. for (let i = 0; i < pars.length; i++)
  201. pars[i]._t = this.repSpaces(pars[i]._t).trim();
  202. return this.formatFb2(fb2);
  203. }
  204. }
  205. module.exports = ConvertHtml;