BookParser.js 11 KB

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