ConvertHtml.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. let {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', 'ul', '/ul', 'h1', 'h2', 'h3', 'h4', 'h5', '/h1', '/h2', '/h3', '/h4', '/h5']);
  64. const newPara2 = new Set(['h1', 'h2', 'h3', 'h4', 'h5']);
  65. const onTextNode = (text, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  66. text = this.escapeEntities(text);
  67. if (!cutCounter && !(cutTitle && inTitle)) {
  68. let tOpen = (bold ? '<strong>' : '');
  69. tOpen += (italic ? '<emphasis>' : '');
  70. let tClose = (italic ? '</emphasis>' : '');
  71. tClose += (bold ? '</strong>' : '');
  72. growParagraph(`${tOpen}${text}${tClose}`);
  73. }
  74. if (inTitle && !title)
  75. title = text;
  76. if (inImage) {
  77. image._t = text;
  78. binary.push(image);
  79. pars.push({_n: 'image', _attrs: {'l:href': '#' + image._attrs.id}, _t: ''});
  80. newParagraph();
  81. }
  82. };
  83. const onStartNode = (tag, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  84. if (!cutCounter) {
  85. if (newPara.has(tag))
  86. newParagraph();
  87. if (newPara2.has(tag))
  88. newParagraph();
  89. switch (tag) {
  90. case 'i':
  91. case 'em':
  92. italic = true;
  93. break;
  94. case 'b':
  95. case 'strong':
  96. case 'h1':
  97. case 'h2':
  98. case 'h3':
  99. bold = true;
  100. break;
  101. }
  102. }
  103. if (tag == 'title' || tag == 'cut-title') {
  104. inTitle = true;
  105. if (tag == 'cut-title')
  106. cutTitle = true;
  107. }
  108. if (tag == 'fb2-image') {
  109. inImage = true;
  110. const attrs = sax.getAttrsSync(tail);
  111. image = {_n: 'binary', _attrs: {id: attrs.name.value, 'content-type': attrs.type.value}, _t: ''};
  112. }
  113. };
  114. const onEndNode = (tag, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  115. if (!cutCounter) {
  116. if (newPara.has('/' + tag))
  117. newParagraph();
  118. if (newPara2.has('/' + tag))
  119. newParagraph();
  120. switch (tag) {
  121. case 'i':
  122. case 'em':
  123. italic = false;
  124. break;
  125. case 'b':
  126. case 'strong':
  127. case 'h1':
  128. case 'h2':
  129. case 'h3':
  130. bold = false;
  131. break;
  132. }
  133. }
  134. if (tag == 'title' || tag == 'cut-title')
  135. inTitle = false;
  136. if (tag == 'fb2-image')
  137. inImage = false;
  138. };
  139. let buf = this.decode(data).toString();
  140. sax.parseSync(buf, {
  141. onStartNode, onEndNode, onTextNode,
  142. innerCut: new Set(['head', 'script', 'style', 'binary', 'fb2-image'])
  143. });
  144. titleInfo['book-title'] = title;
  145. //подозрение на чистый текст, надо разбить на параграфы
  146. if (isText || pars.length < buf.length/2000) {
  147. let total = 0;
  148. let count = 1;
  149. for (let i = 0; i < spaceCounter.length; i++) {
  150. const sc = (spaceCounter[i] ? spaceCounter[i] : 0);
  151. if (sc) count++;
  152. total += sc;
  153. }
  154. let d = 0;
  155. const mid = total/count;
  156. for (let i = 0; i < spaceCounter.length; i++) {
  157. const sc = (spaceCounter[i] ? spaceCounter[i] : 0);
  158. if (sc > mid) d++;
  159. }
  160. let i = 0;
  161. //если разброс не слишком большой, выделяем параграфы
  162. if (d < 10 && spaceCounter.length) {
  163. total /= 20;
  164. i = spaceCounter.length - 1;
  165. while (i > 0 && (!spaceCounter[i] || spaceCounter[i] < total)) i--;
  166. }
  167. const parIndent = (i > 0 ? i : 0);
  168. let newPars = [];
  169. const newPar = () => {
  170. newPars.push({_n: 'p', _t: ''});
  171. };
  172. const growPar = (text) => {
  173. if (!newPars.length)
  174. newPar();
  175. const l = newPars.length;
  176. newPars[l - 1]._t += text;
  177. }
  178. i = 0;
  179. for (const par of pars) {
  180. if (par._n != 'p') {
  181. newPars.push(par);
  182. continue;
  183. }
  184. if (i > 0)
  185. newPar();
  186. i++;
  187. let j = 0;
  188. const lines = par._t.split('\n');
  189. for (let line of lines) {
  190. line = repCrLfTab(line);
  191. let l = 0;
  192. while (l < line.length && line[l] == ' ') {
  193. l++;
  194. }
  195. if (l >= parIndent) {
  196. if (j > 0)
  197. newPar();
  198. j++;
  199. }
  200. growPar(line.trim() + ' ');
  201. }
  202. }
  203. body.section._a[0] = newPars;
  204. } else {
  205. body.section._a[0] = pars;
  206. }
  207. //убираем лишнее, делаем валидный fb2, т.к. в рез-те разбиения на параграфы бьются теги
  208. bold = false;
  209. italic = false;
  210. pars = body.section._a[0];
  211. for (let i = 0; i < pars.length; i++) {
  212. if (pars[i]._n != 'p')
  213. continue;
  214. pars[i]._t = this.repSpaces(pars[i]._t).trim();
  215. if (pars[i]._t.indexOf('<') >= 0 || bold || italic) {
  216. const t = pars[i]._t;
  217. let a = [];
  218. const onTextNode = (text) => {
  219. let tOpen = (bold ? '<strong>' : '');
  220. tOpen += (italic ? '<emphasis>' : '');
  221. let tClose = (italic ? '</emphasis>' : '');
  222. tClose += (bold ? '</strong>' : '');
  223. a.push(`${tOpen}${text}${tClose}`);
  224. }
  225. const onStartNode = (tag) => {
  226. if (tag == 'strong')
  227. bold = true;
  228. if (tag == 'emphasis')
  229. italic = true;
  230. }
  231. const onEndNode = (tag) => {
  232. if (tag == 'strong')
  233. bold = false;
  234. if (tag == 'emphasis')
  235. italic = false;
  236. }
  237. sax.parseSync(t, { onStartNode, onEndNode, onTextNode });
  238. pars[i]._t = '';
  239. pars[i]._a = a;
  240. }
  241. }
  242. return this.formatFb2(fb2);
  243. }
  244. }
  245. module.exports = ConvertHtml;