ConvertHtml.js 11 KB

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