BookParser.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. import EasySAXParser from './easysax';
  2. import {sleep} from '../../../share/utils';
  3. export default class BookParser {
  4. constructor() {
  5. // defaults
  6. this.p = 30;// px, отступ параграфа
  7. this.w = 300;// px, ширина страницы
  8. this.textAlignJustify = false;// выравнивание по ширине
  9. this.wordWrap = false;// перенос по слогам, если textAlignJustify = true
  10. // заглушка
  11. this.measureText = (text, style) => {// eslint-disable-line no-unused-vars
  12. return text.length*10;
  13. };
  14. }
  15. async parse(data, callback) {
  16. if (!callback)
  17. callback = () => {};
  18. callback(0);
  19. this.data = data;
  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 nextPerc = 0;
  33. let paraIndex = -1;
  34. let paraOffset = 0;
  35. let para = []; /*array of
  36. {
  37. index: Number,
  38. offset: Number, //сумма всех length до этого параграфа
  39. length: Number, //длина text без тегов
  40. text: String //текст параграфа (или title или epigraph и т.д) с вложенными тегами
  41. }
  42. */
  43. const newParagraph = (text, len) => {
  44. paraIndex++;
  45. let p = {
  46. index: paraIndex,
  47. offset: paraOffset,
  48. length: len,
  49. text: text
  50. };
  51. para[paraIndex] = p;
  52. paraOffset += p.length;
  53. };
  54. const growParagraph = (text, len) => {
  55. let p = para[paraIndex];
  56. if (p) {
  57. paraOffset -= p.length;
  58. if (p.text == ' ') {
  59. p.length = 0;
  60. p.text = '';
  61. }
  62. p.length += len;
  63. p.text += text;
  64. } else {
  65. p = {
  66. index: paraIndex,
  67. offset: paraOffset,
  68. length: len,
  69. text: text
  70. };
  71. }
  72. para[paraIndex] = p;
  73. paraOffset += p.length;
  74. };
  75. const parser = new EasySAXParser();
  76. parser.on('error', (msgError) => {// eslint-disable-line no-unused-vars
  77. });
  78. parser.on('startNode', (elemName, getAttr, isTagEnd, getStrNode) => {// eslint-disable-line no-unused-vars
  79. tag = elemName;
  80. path += '/' + elemName;
  81. if ((tag == 'p' || tag == 'empty-line') && path.indexOf('/FictionBook/body/section') == 0) {
  82. newParagraph(' ', 1);
  83. }
  84. });
  85. parser.on('endNode', (elemName, isTagStart, getStrNode) => {// eslint-disable-line no-unused-vars
  86. if (tag == elemName) {
  87. path = path.substr(0, path.length - tag.length - 1);
  88. let i = path.lastIndexOf('/');
  89. if (i >= 0) {
  90. tag = path.substr(i + 1);
  91. } else {
  92. tag = path;
  93. }
  94. }
  95. });
  96. parser.on('textNode', (text) => {
  97. text = text.trim();
  98. switch (path) {
  99. case '/FictionBook/description/title-info/author/first-name':
  100. fb2.firstName = text;
  101. break;
  102. case '/FictionBook/description/title-info/author/middle-name':
  103. fb2.middleName = text;
  104. break;
  105. case '/FictionBook/description/title-info/author/last-name':
  106. fb2.lastName = text;
  107. break;
  108. case '/FictionBook/description/title-info/genre':
  109. fb2.genre = text;
  110. break;
  111. case '/FictionBook/description/title-info/date':
  112. fb2.date = text;
  113. break;
  114. case '/FictionBook/description/title-info/book-title':
  115. fb2.bookTitle = text;
  116. break;
  117. case '/FictionBook/description/title-info/id':
  118. fb2.id = text;
  119. break;
  120. }
  121. if (path.indexOf('/FictionBook/description/title-info/annotation') == 0) {
  122. if (!fb2.annotation)
  123. fb2.annotation = '';
  124. if (tag != 'annotation')
  125. fb2.annotation += `<${tag}>${text}</${tag}>`;
  126. else
  127. fb2.annotation += text;
  128. }
  129. if (text == '')
  130. return;
  131. if (path.indexOf('/FictionBook/body/title') == 0) {
  132. newParagraph(text, text.length);
  133. }
  134. if (text == '')
  135. return;
  136. if (path.indexOf('/FictionBook/body/section') == 0) {
  137. switch (tag) {
  138. case 'p':
  139. growParagraph(text, text.length);
  140. break;
  141. case 'section':
  142. case 'title':
  143. newParagraph(text, text.length);
  144. break;
  145. default:
  146. growParagraph(`<${tag}>${text}</${tag}>`, text.length);
  147. }
  148. }
  149. });
  150. parser.on('cdata', (data) => {// eslint-disable-line no-unused-vars
  151. });
  152. parser.on('comment', (text) => {// eslint-disable-line no-unused-vars
  153. });
  154. parser.on('progress', async(progress) => {
  155. if (progress > nextPerc) {
  156. await sleep(1);
  157. callback(progress);
  158. nextPerc += 10;
  159. }
  160. });
  161. await parser.parse(data);
  162. this.fb2 = fb2;
  163. this.para = para;
  164. callback(100);
  165. await sleep(10);
  166. return {fb2};
  167. }
  168. findParaIndex(bookPos) {
  169. let result = undefined;
  170. //дихотомия
  171. let first = 0;
  172. let last = this.para.length - 1;
  173. while (first < last) {
  174. let mid = first + Math.floor((last - first)/2);
  175. if (bookPos <= this.para[mid].offset + this.para[mid].length - 1)
  176. last = mid;
  177. else
  178. first = mid + 1;
  179. }
  180. if (last >= 0) {
  181. const ofs = this.para[last].offset;
  182. if (bookPos >= ofs && bookPos < ofs + this.para[last].length)
  183. result = last;
  184. }
  185. return result;
  186. }
  187. removeTags(s) {
  188. let result = '';
  189. const parser = new EasySAXParser();
  190. parser.on('textNode', (text) => {
  191. result += text;
  192. });
  193. parser.parse(`<p>${s}</p>`);
  194. return result;
  195. }
  196. parsePara(paraIndex) {
  197. const para = this.para[paraIndex];
  198. if (para.parsed &&
  199. para.parsed.w === this.w &&
  200. para.parsed.p === this.p &&
  201. para.parsed.textAlignJustify === this.textAlignJustify &&
  202. para.parsed.wordWrap === this.wordWrap)
  203. return para.parsed;
  204. const parsed = {
  205. w: this.w,
  206. p: this.p,
  207. textAlignJustify: this.textAlignJustify,
  208. wordWrap: this.wordWrap
  209. };
  210. const lines = [];
  211. /* array of
  212. {
  213. begin: Number,
  214. end: Number,
  215. parts: array of {
  216. style: 'bold'|'italic',
  217. text: String,
  218. }
  219. }*/
  220. const text = this.removeTags(para.text);
  221. const words = text.split(' ');
  222. let line = {begin: para.offset, parts: []};
  223. let part = '';
  224. let j = 0;
  225. let k = 0;
  226. // тут начинается самый замес, перенос и выравниване по ширине
  227. for (let i = 0; i < words.length; i++) {
  228. const word = words[i];
  229. if (j > 0)
  230. part += ' ';
  231. j++;
  232. part += word;
  233. if (this.measureText(part) >= parsed.w || i == words.length - 1) {
  234. line.parts.push({style: '', text: (k == 0 ? ' ' : '') + part});
  235. line.end = line.begin + part.length - 1;
  236. lines.push(line);
  237. line = {begin: line.end + 1, parts: []};
  238. part = '';
  239. j = 0;
  240. k++;
  241. }
  242. }
  243. parsed.lines = lines;
  244. para.parsed = parsed;
  245. return parsed;
  246. }
  247. findLineIndex(bookPos, lines) {
  248. let result = undefined;
  249. //дихотомия
  250. let first = 0;
  251. let last = lines.length - 1;
  252. while (first < last) {
  253. let mid = first + Math.floor((last - first)/2);
  254. if (bookPos <= lines[mid].end)
  255. last = mid;
  256. else
  257. first = mid + 1;
  258. }
  259. if (last >= 0) {
  260. if (bookPos >= lines[last].begin && bookPos <= lines[last].end)
  261. result = last;
  262. }
  263. return result;
  264. }
  265. getLines(bookPos, n) {
  266. const result = [];
  267. let paraIndex = this.findParaIndex(bookPos);
  268. if (paraIndex === undefined)
  269. return result;
  270. if (n > 0) {
  271. let parsed = this.parsePara(paraIndex);
  272. let i = this.findLineIndex(bookPos, parsed.lines);
  273. if (i === undefined)
  274. return result;
  275. while (n > 0) {
  276. result.push(parsed.lines[i]);
  277. i++;
  278. if (i >= parsed.lines.length) {
  279. paraIndex++;
  280. if (paraIndex < this.para.length)
  281. parsed = this.parsePara(paraIndex);
  282. else
  283. return result;
  284. i = 0;
  285. }
  286. n--;
  287. }
  288. } else if (n < 0) {
  289. n = -n;
  290. let parsed = this.parsePara(paraIndex);
  291. let i = this.findLineIndex(bookPos, parsed.lines);
  292. if (i === undefined)
  293. return result;
  294. while (n > 0) {
  295. result.push(parsed.lines[i]);
  296. i--;
  297. if (i < 0) {
  298. paraIndex--;
  299. if (paraIndex >= 0)
  300. parsed = this.parsePara(paraIndex);
  301. else
  302. return result;
  303. i = parsed.lines.length - 1;
  304. }
  305. n--;
  306. }
  307. }
  308. return result;
  309. }
  310. }