BookParser.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. import he from 'he';
  2. import sax from '../../../../server/core/BookConverter/sax';
  3. import {sleep} from '../../../share/utils';
  4. export default class BookParser {
  5. constructor() {
  6. // defaults
  7. this.p = 30;// px, отступ параграфа
  8. this.w = 300;// px, ширина страницы
  9. this.wordWrap = false;// перенос по слогам
  10. //заглушка
  11. this.measureText = (text, style) => {// eslint-disable-line no-unused-vars
  12. return text.length*20;
  13. };
  14. }
  15. async parse(data, callback) {
  16. if (!callback)
  17. callback = () => {};
  18. callback(0);
  19. if (data.indexOf('<FictionBook') < 0) {
  20. throw new Error('Неверный формат файла');
  21. }
  22. //defaults
  23. let fb2 = {
  24. firstName: '',
  25. middleName: '',
  26. lastName: '',
  27. bookTitle: '',
  28. };
  29. let path = '';
  30. let tag = '';
  31. let center = false;
  32. let bold = false;
  33. let italic = false;
  34. let paraIndex = -1;
  35. let paraOffset = 0;
  36. let para = []; /*array of
  37. {
  38. index: Number,
  39. offset: Number, //сумма всех length до этого параграфа
  40. length: Number, //длина text без тегов
  41. text: String, //текст параграфа с вложенными тегами
  42. cut: Boolean, //параграф - кандидат на сокрытие (cutEmptyParagraphs)
  43. addIndex: Number, //индекс добавляемого пустого параграфа (addEmptyParagraphs)
  44. }
  45. */
  46. const newParagraph = (text, len, addIndex) => {
  47. paraIndex++;
  48. let p = {
  49. index: paraIndex,
  50. offset: paraOffset,
  51. length: len,
  52. text: text,
  53. cut: (!addIndex && (len == 1 && text[0] == ' ')),
  54. addIndex: (addIndex ? addIndex : 0),
  55. };
  56. para[paraIndex] = p;
  57. paraOffset += p.length;
  58. };
  59. const growParagraph = (text, len) => {
  60. if (paraIndex < 0) {
  61. newParagraph(' ', 1);
  62. growParagraph(text, len);
  63. return;
  64. }
  65. let p = para[paraIndex];
  66. //добавление пустых (addEmptyParagraphs) параграфов
  67. if (p.length == 1 && p.text[0] == ' ' && len > 0) {
  68. paraIndex--;
  69. paraOffset -= p.length;
  70. for (let i = 0; i < 2; i++) {
  71. newParagraph(' ', 1, i + 1);
  72. }
  73. paraIndex++;
  74. p.index = paraIndex;
  75. p.offset = paraOffset;
  76. para[paraIndex] = p;
  77. paraOffset += p.length;
  78. }
  79. paraOffset -= p.length;
  80. //параграф оказался непустой
  81. if (p.length == 1 && p.text[0] == ' ' && len > 0) {
  82. p.length = 0;
  83. p.text = p.text.substr(1);
  84. p.cut = (len == 1 && text[0] == ' ');
  85. }
  86. p.length += len;
  87. p.text += text;
  88. para[paraIndex] = p;
  89. paraOffset += p.length;
  90. };
  91. const onStartNode = (elemName) => {// eslint-disable-line no-unused-vars
  92. if (elemName == '?xml')
  93. return;
  94. tag = elemName;
  95. path += '/' + elemName;
  96. if (path.indexOf('/fictionbook/body') == 0) {
  97. if (tag == 'title') {
  98. newParagraph(' ', 1);
  99. bold = true;
  100. center = true;
  101. }
  102. if (tag == 'emphasis' || tag == 'strong') {
  103. growParagraph(`<${tag}>`, 0);
  104. }
  105. if ((tag == 'p' || tag == 'empty-line' || tag == 'v')) {
  106. newParagraph(' ', 1);
  107. }
  108. if (tag == 'subtitle') {
  109. newParagraph(' ', 1);
  110. bold = true;
  111. }
  112. if (tag == 'epigraph') {
  113. italic = true;
  114. }
  115. if (tag == 'poem') {
  116. newParagraph(' ', 1);
  117. }
  118. if (tag == 'text-author') {
  119. newParagraph(' <s> <s> <s> ', 4);
  120. }
  121. }
  122. };
  123. const onEndNode = (elemName) => {// eslint-disable-line no-unused-vars
  124. if (tag == elemName) {
  125. if (path.indexOf('/fictionbook/body') == 0) {
  126. if (tag == 'title') {
  127. bold = false;
  128. center = false;
  129. }
  130. if (tag == 'emphasis' || tag == 'strong') {
  131. growParagraph(`</${tag}>`, 0);
  132. }
  133. if (tag == 'subtitle') {
  134. bold = false;
  135. }
  136. if (tag == 'epigraph') {
  137. italic = false;
  138. }
  139. if (tag == 'stanza') {
  140. newParagraph(' ', 1);
  141. }
  142. }
  143. path = path.substr(0, path.length - tag.length - 1);
  144. let i = path.lastIndexOf('/');
  145. if (i >= 0) {
  146. tag = path.substr(i + 1);
  147. } else {
  148. tag = path;
  149. }
  150. }
  151. };
  152. const onTextNode = (text) => {// eslint-disable-line no-unused-vars
  153. text = he.decode(text);
  154. text = text.replace(/>/g, '&gt;');
  155. text = text.replace(/</g, '&lt;');
  156. if (text != ' ' && text.trim() == '')
  157. text = text.trim();
  158. if (text == '')
  159. return;
  160. text = text.replace(/[\t\n\r]/g, ' ');
  161. switch (path) {
  162. case '/fictionbook/description/title-info/author/first-name':
  163. fb2.firstName = text;
  164. break;
  165. case '/fictionbook/description/title-info/author/middle-name':
  166. fb2.middleName = text;
  167. break;
  168. case '/fictionbook/description/title-info/author/last-name':
  169. fb2.lastName = text;
  170. break;
  171. case '/fictionbook/description/title-info/genre':
  172. fb2.genre = text;
  173. break;
  174. case '/fictionbook/description/title-info/date':
  175. fb2.date = text;
  176. break;
  177. case '/fictionbook/description/title-info/book-title':
  178. fb2.bookTitle = text;
  179. break;
  180. case '/fictionbook/description/title-info/id':
  181. fb2.id = text;
  182. break;
  183. }
  184. if (path.indexOf('/fictionbook/description/title-info/annotation') == 0) {
  185. if (!fb2.annotation)
  186. fb2.annotation = '';
  187. if (tag != 'annotation')
  188. fb2.annotation += `<${tag}>${text}</${tag}>`;
  189. else
  190. fb2.annotation += text;
  191. }
  192. let tOpen = (center ? '<center>' : '');
  193. tOpen += (bold ? '<strong>' : '');
  194. tOpen += (italic ? '<emphasis>' : '');
  195. let tClose = (italic ? '</emphasis>' : '');
  196. tClose += (bold ? '</strong>' : '');
  197. tClose += (center ? '</center>' : '');
  198. if (path.indexOf('/fictionbook/body/title') == 0) {
  199. growParagraph(`${tOpen}${text}${tClose}`, text.length);
  200. }
  201. if (path.indexOf('/fictionbook/body/section') == 0) {
  202. switch (tag) {
  203. case 'p':
  204. growParagraph(`${tOpen}${text}${tClose}`, text.length);
  205. break;
  206. default:
  207. growParagraph(`${tOpen}${text}${tClose}`, text.length);
  208. }
  209. }
  210. };
  211. const onProgress = async(prog) => {
  212. await sleep(1);
  213. callback(prog);
  214. };
  215. await sax.parse(data, {
  216. onStartNode, onEndNode, onTextNode, onProgress
  217. });
  218. this.fb2 = fb2;
  219. this.para = para;
  220. this.textLength = paraOffset;
  221. callback(100);
  222. await sleep(10);
  223. return {fb2};
  224. }
  225. findParaIndex(bookPos) {
  226. let result = undefined;
  227. //дихотомия
  228. let first = 0;
  229. let last = this.para.length - 1;
  230. while (first < last) {
  231. let mid = first + Math.floor((last - first)/2);
  232. if (bookPos <= this.para[mid].offset + this.para[mid].length - 1)
  233. last = mid;
  234. else
  235. first = mid + 1;
  236. }
  237. if (last >= 0) {
  238. const ofs = this.para[last].offset;
  239. if (bookPos >= ofs && bookPos < ofs + this.para[last].length)
  240. result = last;
  241. }
  242. return result;
  243. }
  244. splitToStyle(s) {
  245. let result = [];/*array of {
  246. style: {bold: Boolean, italic: Boolean, center: Boolean},
  247. text: String,
  248. }*/
  249. let style = {};
  250. const onTextNode = async(text) => {// eslint-disable-line no-unused-vars
  251. result.push({
  252. style: Object.assign({}, style),
  253. text: text
  254. });
  255. };
  256. const onStartNode = async(elemName) => {// eslint-disable-line no-unused-vars
  257. switch (elemName) {
  258. case 'strong':
  259. style.bold = true;
  260. break;
  261. case 'emphasis':
  262. style.italic = true;
  263. break;
  264. case 'center':
  265. style.center = true;
  266. break;
  267. }
  268. };
  269. const onEndNode = async(elemName) => {// eslint-disable-line no-unused-vars
  270. switch (elemName) {
  271. case 'strong':
  272. style.bold = false;
  273. break;
  274. case 'emphasis':
  275. style.italic = false;
  276. break;
  277. case 'center':
  278. style.center = false;
  279. break;
  280. }
  281. };
  282. sax.parseSync(s, {
  283. onStartNode, onEndNode, onTextNode
  284. });
  285. //длинные слова (или белиберду без пробелов) тоже разобьем
  286. const maxWordLength = this.maxWordLength;
  287. const parts = result;
  288. result = [];
  289. for (const part of parts) {
  290. let p = part;
  291. let i = 0;
  292. let spaceIndex = -1;
  293. while (i < p.text.length) {
  294. if (p.text[i] == ' ')
  295. spaceIndex = i;
  296. if (i - spaceIndex >= maxWordLength && i < p.text.length - 1 &&
  297. this.measureText(p.text.substr(spaceIndex + 1, i - spaceIndex), p.style) >= this.w - this.p) {
  298. result.push({style: p.style, text: p.text.substr(0, i + 1)});
  299. p = {style: p.style, text: p.text.substr(i + 1)};
  300. spaceIndex = -1;
  301. i = -1;
  302. }
  303. i++;
  304. }
  305. result.push(p);
  306. }
  307. return result;
  308. }
  309. splitToSlogi(word) {
  310. let result = [];
  311. const glas = new Set(['а', 'А', 'о', 'О', 'и', 'И', 'е', 'Е', 'ё', 'Ё', 'э', 'Э', 'ы', 'Ы', 'у', 'У', 'ю', 'Ю', 'я', 'Я']);
  312. const soglas = new Set([
  313. 'б', 'в', 'г', 'д', 'ж', 'з', 'й', 'к', 'л', 'м', 'н', 'п', 'р', 'с', 'т', 'ф', 'х', 'ц', 'ч', 'ш', 'щ',
  314. 'Б', 'В', 'Г', 'Д', 'Ж', 'З', 'Й', 'К', 'Л', 'М', 'Н', 'П', 'Р', 'С', 'Т', 'Ф', 'Х', 'Ч', 'Ц', 'Ш', 'Щ'
  315. ]);
  316. const znak = new Set(['ь', 'Ь', 'ъ', 'Ъ', 'й', 'Й']);
  317. const alpha = new Set([...glas, ...soglas, ...znak]);
  318. let slog = '';
  319. let slogLen = 0;
  320. const len = word.length;
  321. word += ' ';
  322. for (let i = 0; i < len; i++) {
  323. slog += word[i];
  324. if (alpha.has(word[i]))
  325. slogLen++;
  326. if (slogLen > 1 && i < len - 2 && (
  327. //гласная, а следом не 2 согласные буквы
  328. (glas.has(word[i]) && !(soglas.has(word[i + 1]) &&
  329. soglas.has(word[i + 2])) && alpha.has(word[i + 1]) && alpha.has(word[i + 2])
  330. ) ||
  331. //предыдущая не согласная буква, текущая согласная, а следом согласная и согласная|гласная буквы
  332. (alpha.has(word[i - 1]) && !soglas.has(word[i - 1]) &&
  333. soglas.has(word[i]) && soglas.has(word[i + 1]) &&
  334. (glas.has(word[i + 2]) || soglas.has(word[i + 2])) &&
  335. alpha.has(word[i + 1]) && alpha.has(word[i + 2])
  336. ) ||
  337. //мягкий или твердый знак или Й
  338. (znak.has(word[i]) && alpha.has(word[i + 1]) && alpha.has(word[i + 2])) ||
  339. (word[i] == '-')
  340. ) &&
  341. //нельзя оставлять окончания на ь, ъ, й
  342. !(znak.has(word[i + 2]) && !alpha.has(word[i + 3]))
  343. ) {
  344. result.push(slog);
  345. slog = '';
  346. slogLen = 0;
  347. }
  348. }
  349. if (slog)
  350. result.push(slog);
  351. return result;
  352. }
  353. parsePara(paraIndex) {
  354. const para = this.para[paraIndex];
  355. if (!this.force &&
  356. para.parsed &&
  357. para.parsed.w === this.w &&
  358. para.parsed.p === this.p &&
  359. para.parsed.wordWrap === this.wordWrap &&
  360. para.parsed.maxWordLength === this.maxWordLength &&
  361. para.parsed.font === this.font &&
  362. para.parsed.cutEmptyParagraphs === this.cutEmptyParagraphs &&
  363. para.parsed.addEmptyParagraphs === this.addEmptyParagraphs
  364. )
  365. return para.parsed;
  366. const parsed = {
  367. w: this.w,
  368. p: this.p,
  369. wordWrap: this.wordWrap,
  370. maxWordLength: this.maxWordLength,
  371. font: this.font,
  372. cutEmptyParagraphs: this.cutEmptyParagraphs,
  373. addEmptyParagraphs: this.addEmptyParagraphs,
  374. visible: !(
  375. (this.cutEmptyParagraphs && para.cut) ||
  376. (para.addIndex > this.addEmptyParagraphs)
  377. )
  378. };
  379. const lines = []; /* array of
  380. {
  381. begin: Number,
  382. end: Number,
  383. first: Boolean,
  384. last: Boolean,
  385. parts: array of {
  386. style: {bold: Boolean, italic: Boolean, center: Boolean},
  387. text: String,
  388. }
  389. }*/
  390. let parts = this.splitToStyle(para.text);
  391. let line = {begin: para.offset, parts: []};
  392. let partText = '';//накапливаемый кусок со стилем
  393. let str = '';//измеряемая строка
  394. let prevStr = '';//строка без крайнего слова
  395. let prevW = 0;
  396. let j = 0;//номер строки
  397. let style = {};
  398. let ofs = 0;//смещение от начала параграфа para.offset
  399. // тут начинается самый замес, перенос по слогам и стилизация
  400. for (const part of parts) {
  401. const words = part.text.split(' ');
  402. style = part.style;
  403. let sp1 = '';
  404. let sp2 = '';
  405. for (let i = 0; i < words.length; i++) {
  406. const word = words[i];
  407. ofs += word.length + (i < words.length - 1 ? 1 : 0);
  408. if (word == '' && i > 0 && i < words.length - 1)
  409. continue;
  410. str += sp1 + word;
  411. let p = (j == 0 ? parsed.p : 0);
  412. let w = this.measureText(str, style) + p;
  413. let wordTail = word;
  414. if (w > parsed.w && prevStr != '') {
  415. if (parsed.wordWrap) {//по слогам
  416. let slogi = this.splitToSlogi(word);
  417. if (slogi.length > 1) {
  418. let s = prevStr + sp1;
  419. let ss = sp1;
  420. let pw;
  421. const slogiLen = slogi.length;
  422. for (let k = 0; k < slogiLen - 1; k++) {
  423. let slog = slogi[0];
  424. let ww = this.measureText(s + slog + (slog[slog.length - 1] == '-' ? '' : '-'), style) + p;
  425. if (ww <= parsed.w) {
  426. s += slog;
  427. ss += slog;
  428. } else
  429. break;
  430. pw = ww;
  431. slogi.shift();
  432. }
  433. if (pw) {
  434. prevW = pw;
  435. partText += ss + (ss[ss.length - 1] == '-' ? '' : '-');
  436. wordTail = slogi.join('');
  437. }
  438. }
  439. }
  440. if (partText != '')
  441. line.parts.push({style, text: partText});
  442. if (line.parts.length) {//корявенько, коррекция при переносе, отрефакторить не вышло
  443. let t = line.parts[line.parts.length - 1].text;
  444. if (t[t.length - 1] == ' ') {
  445. line.parts[line.parts.length - 1].text = t.trimRight();
  446. prevW -= this.measureText(' ', style);
  447. }
  448. }
  449. line.end = para.offset + ofs - wordTail.length - 1 - (i < words.length - 1 ? 1 : 0);
  450. if (line.end - line.begin < 0)
  451. console.error(`Parse error, empty line in paragraph ${paraIndex}`);
  452. line.width = prevW;
  453. line.first = (j == 0);
  454. line.last = false;
  455. lines.push(line);
  456. line = {begin: line.end + 1, parts: []};
  457. partText = '';
  458. sp2 = '';
  459. str = wordTail;
  460. j++;
  461. }
  462. prevStr = str;
  463. partText += sp2 + wordTail;
  464. sp1 = ' ';
  465. sp2 = ' ';
  466. prevW = w;
  467. }
  468. if (partText != '')
  469. line.parts.push({style, text: partText});
  470. partText = '';
  471. }
  472. if (line.parts.length) {//корявенько, коррекция при переносе
  473. let t = line.parts[line.parts.length - 1].text;
  474. if (t[t.length - 1] == ' ') {
  475. line.parts[line.parts.length - 1].text = t.trimRight();
  476. prevW -= this.measureText(' ', style);
  477. }
  478. line.end = para.offset + para.length - 1;
  479. if (line.end - line.begin < 0)
  480. console.error(`Parse error, empty line in paragraph ${paraIndex}`);
  481. line.width = prevW;
  482. line.first = (j == 0);
  483. line.last = true;
  484. lines.push(line);
  485. } else {//подстраховка
  486. if (lines.length) {
  487. line = lines[lines.length - 1];
  488. const end = para.offset + para.length - 1;
  489. if (line.end != end)
  490. console.error(`Parse error, wrong end in paragraph ${paraIndex}`);
  491. line.end = end;
  492. }
  493. }
  494. parsed.lines = lines;
  495. para.parsed = parsed;
  496. return parsed;
  497. }
  498. findLineIndex(bookPos, lines) {
  499. let result = undefined;
  500. //дихотомия
  501. let first = 0;
  502. let last = lines.length - 1;
  503. while (first < last) {
  504. let mid = first + Math.floor((last - first)/2);
  505. if (bookPos <= lines[mid].end)
  506. last = mid;
  507. else
  508. first = mid + 1;
  509. }
  510. if (last >= 0) {
  511. if (bookPos >= lines[last].begin && bookPos <= lines[last].end)
  512. result = last;
  513. }
  514. return result;
  515. }
  516. getLines(bookPos, n) {
  517. let result = [];
  518. let paraIndex = this.findParaIndex(bookPos);
  519. if (paraIndex === undefined)
  520. return null;
  521. if (n > 0) {
  522. let parsed = this.parsePara(paraIndex);
  523. let i = this.findLineIndex(bookPos, parsed.lines);
  524. if (i === undefined)
  525. return null;
  526. while (n > 0) {
  527. if (parsed.visible) {
  528. result.push(parsed.lines[i]);
  529. n--;
  530. }
  531. i++;
  532. if (i >= parsed.lines.length) {
  533. paraIndex++;
  534. if (paraIndex < this.para.length)
  535. parsed = this.parsePara(paraIndex);
  536. else
  537. break;
  538. i = 0;
  539. }
  540. }
  541. } else if (n < 0) {
  542. n = -n;
  543. let parsed = this.parsePara(paraIndex);
  544. let i = this.findLineIndex(bookPos, parsed.lines);
  545. if (i === undefined)
  546. return null;
  547. while (n > 0) {
  548. if (parsed.visible) {
  549. result.push(parsed.lines[i]);
  550. n--;
  551. }
  552. i--;
  553. if (i < 0) {
  554. paraIndex--;
  555. if (paraIndex >= 0)
  556. parsed = this.parsePara(paraIndex);
  557. else
  558. break;
  559. i = parsed.lines.length - 1;
  560. }
  561. }
  562. }
  563. if (!result.length)
  564. result = null;
  565. return result;
  566. }
  567. }