ConvertHtml.js 11 KB

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