BookParser.js 25 KB

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