ConvertHtml.js 11 KB

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