ConvertHtml.js 8.9 KB

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