BookParser.js 22 KB

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