ConvertHtml.js 10 KB

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