ConvertHtml.js 9.0 KB

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