index.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. const fs = require('fs-extra');
  2. const URL = require('url').URL;
  3. const iconv = require('iconv-lite');
  4. const chardet = require('chardet');
  5. const _ = require('lodash');
  6. const FileDetector = require('../FileDetector');
  7. const EasySAXParser = require('./easysaxmod');
  8. class BookConverter {
  9. constructor() {
  10. this.detector = new FileDetector();
  11. }
  12. async convertToFb2(inputFile, outputFile, url, callback) {
  13. const fileType = await this.detector.detectFile(inputFile);
  14. if (fileType && (fileType.ext == 'html' || fileType.ext == 'xml')) {
  15. const data = await fs.readFile(inputFile);
  16. if (data.toString().indexOf('<FictionBook') >= 0) {
  17. await fs.writeFile(outputFile, data);
  18. return;
  19. }
  20. const parsedUrl = new URL(url);
  21. if (parsedUrl.hostname == 'samlib.ru' ||
  22. parsedUrl.hostname == 'budclub.ru') {
  23. await fs.writeFile(outputFile, await this.convertSamlib(data));
  24. return;
  25. }
  26. //Заглушка
  27. await fs.writeFile(outputFile, await this.convertHtml(data));
  28. callback(100);
  29. } else {
  30. if (fileType)
  31. throw new Error(`unknown file format: ${fileType.mime}`);
  32. else
  33. throw new Error(`unsupported file format: ${url}`);
  34. }
  35. }
  36. decode(data) {
  37. const charsetAll = chardet.detectAll(data.slice(0, 10000));
  38. let selected = 'ISO-8859-1';
  39. for (const charset of charsetAll) {
  40. if (charset.name.indexOf('ISO-8859') < 0) {
  41. selected = charset.name;
  42. break;
  43. }
  44. }
  45. return iconv.decode(data, selected);
  46. }
  47. parseHtml(buf, onNode, onText, innerCut) {
  48. if (!onNode)
  49. onNode = () => {};
  50. if (!onText)
  51. onText = () => {};
  52. if (!innerCut)
  53. innerCut = new Set();
  54. buf = buf.replace(/&nbsp;/g, ' ');
  55. let i = 0;
  56. const len = buf.length;
  57. let cutCounter = 0;
  58. let cutTag = '';
  59. while (i < len) {
  60. let left = buf.indexOf('<', i);
  61. if (left < 0)
  62. break;
  63. let right = buf.indexOf('>', left + 1);
  64. if (right < 0)
  65. break;
  66. let tag = buf.substr(left + 1, right - left - 1).trim().toLowerCase();
  67. let tail = '';
  68. const firstSpace = tag.indexOf(' ');
  69. if (firstSpace >= 0) {
  70. tail = tag.substr(firstSpace + 1);
  71. tag = tag.substr(0, firstSpace);
  72. }
  73. const text = buf.substr(i, left - i);
  74. onText(text, cutCounter, cutTag);
  75. onNode(tag, tail, cutCounter, cutTag);
  76. if (innerCut.has(tag) && (!cutCounter || cutTag == tag)) {
  77. if (!cutCounter)
  78. cutTag = tag;
  79. cutCounter++;
  80. }
  81. if (tag != '' && tag.charAt(0) == '/' && cutTag == tag.substr(1)) {
  82. cutCounter = (cutCounter > 0 ? cutCounter - 1 : 0);
  83. if (!cutCounter)
  84. cutTag = '';
  85. }
  86. i = right + 1;
  87. }
  88. if (i < len)
  89. onText(buf.substr(i, len - i), cutCounter, cutTag);
  90. }
  91. convertHtml(data, isText) {
  92. let titleInfo = {};
  93. let desc = {_n: 'description', 'title-info': titleInfo};
  94. let pars = [];
  95. let body = {_n: 'body', section: {_a: []}};
  96. let fb2 = [desc, body];
  97. let title = '';
  98. let inTitle = false;
  99. let spaceCounter = [];
  100. const newParagraph = () => {
  101. pars.push({_n: 'p', _t: ''});
  102. };
  103. const growParagraph = (text) => {
  104. const l = pars.length;
  105. if (l) {
  106. if (pars[l - 1]._t == '')
  107. text = text.trimLeft();
  108. pars[l - 1]._t += text;
  109. }
  110. //посчитаем отступы у текста, чтобы выделить потом параграфы
  111. const lines = text.split('\n');
  112. for (const line of lines) {
  113. const sp = line.split(' ');
  114. let l = 0;
  115. while (l < sp.length && sp[l].trim() == '') {
  116. l++;
  117. }
  118. if (!spaceCounter[l])
  119. spaceCounter[l] = 0;
  120. spaceCounter[l]++;
  121. }
  122. };
  123. newParagraph();
  124. const newPara = new Set(['tr', 'br', 'br/', 'dd', 'p', 'title', '/title', 'h1', 'h2', 'h3', '/h1', '/h2', '/h3']);
  125. const onText = (text, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  126. if (!cutCounter) {
  127. growParagraph(text);
  128. }
  129. if (inTitle && !title)
  130. title = text;
  131. };
  132. const onNode = (tag, tail, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  133. if (!cutCounter) {
  134. if (newPara.has(tag))
  135. newParagraph();
  136. }
  137. if (tag == 'title')
  138. inTitle = true;
  139. else if (tag == '/title')
  140. inTitle = false;
  141. };
  142. let buf = this.decode(data).toString();
  143. this.parseHtml(buf, onNode, onText, new Set(['head', 'script', 'style']));
  144. titleInfo['book-title'] = title;
  145. //подозрение на чистый текст, надо разбить на параграфы
  146. if ((isText || pars.length < buf.length/2000) && spaceCounter.length) {
  147. let total = 0;
  148. for (let i = 0; i < spaceCounter.length; i++) {
  149. total += (spaceCounter[i] ? spaceCounter[i] : 0);
  150. }
  151. total /= 10;
  152. let i = spaceCounter.length - 1;
  153. while (i > 0 && (!spaceCounter[i] || spaceCounter[i] < total)) i--;
  154. const parIndent = i;
  155. if (parIndent > 0) {//нашли отступ параграфа
  156. let newPars = [];
  157. const newPar = () => {
  158. newPars.push({_n: 'p', _t: ''});
  159. };
  160. const growPar = (text) => {
  161. const l = newPars.length;
  162. if (l) {
  163. newPars[l - 1]._t += text;
  164. }
  165. }
  166. for (const par of pars) {
  167. newPar();
  168. const lines = par._t.split('\n');
  169. for (const line of lines) {
  170. const sp = line.split(' ');
  171. let l = 0;
  172. while (l < sp.length && sp[l].trim() == '') {
  173. l++;
  174. }
  175. if (l >= parIndent)
  176. newPar();
  177. growPar(line.trim() + ' ');
  178. }
  179. }
  180. body.section._a[0] = newPars;
  181. } else {
  182. body.section._a[0] = pars;
  183. }
  184. } else {
  185. body.section._a[0] = pars;
  186. }
  187. //убрать лишнее
  188. for (let p of body.section._a[0]) {
  189. p._t = p._t.replace(/[\t\n\r]/g, ' ');
  190. }
  191. return this.formatFb2(fb2);
  192. }
  193. async convertSamlib(data) {
  194. let titleInfo = {};
  195. let desc = {_n: 'description', 'title-info': titleInfo};
  196. let pars = [];
  197. let body = {_n: 'body', section: {_a: [pars]}};
  198. let fb2 = [desc, body];
  199. let path = '';
  200. let tag = '';// eslint-disable-line no-unused-vars
  201. let inText = false;
  202. let center = false;
  203. //let italic = false;
  204. //let bold = false;
  205. let node = {};
  206. const newParagraph = () => {
  207. node = {_n: 'p', _t: ''};
  208. pars.push(node);
  209. };
  210. const newSubTitle = () => {
  211. node = {_n: 'subtitle', _t: ''};
  212. pars.push(node);
  213. };
  214. const newItalic = () => {
  215. let n = {_n: 'emphasis', _t: ''};
  216. if (!node._a)
  217. node._a = [];
  218. node._a.push(n);
  219. node = n;
  220. };
  221. const newBold = () => {
  222. let n = {_n: 'strong', _t: ''};
  223. if (!node._a)
  224. node._a = [];
  225. node._a.push(n);
  226. node = n;
  227. };
  228. const growParagraph = (text) => {
  229. if (node._t == '')
  230. text = text.trimLeft();
  231. node._t += text;
  232. };
  233. newParagraph();
  234. const parser = new EasySAXParser();
  235. parser.on('error', (msgError) => {// eslint-disable-line no-unused-vars
  236. });
  237. parser.on('startNode', (elemName, getAttr, isTagEnd, getStrNode) => {// eslint-disable-line no-unused-vars
  238. if (!inText) {
  239. path += '/' + elemName;
  240. tag = elemName;
  241. } else {
  242. if (!center && (elemName == 'p' || elemName == 'dd')) {
  243. newParagraph();
  244. }
  245. switch (elemName) {
  246. case 'i':
  247. newItalic();
  248. //italic = true;
  249. break;
  250. case 'b':
  251. newBold();
  252. //bold = true;
  253. break;
  254. case 'div':
  255. var a = getAttr();
  256. if (a && a.align == 'center') {
  257. newSubTitle();
  258. center = true;
  259. }
  260. break;
  261. }
  262. }
  263. });
  264. parser.on('endNode', (elemName, isTagStart, getStrNode) => {// eslint-disable-line no-unused-vars
  265. if (!inText) {
  266. const oldPath = path;
  267. let t = '';
  268. do {
  269. let i = path.lastIndexOf('/');
  270. t = path.substr(i + 1);
  271. path = path.substr(0, i);
  272. } while (t != elemName && path);
  273. if (t != elemName) {
  274. path = oldPath;
  275. }
  276. let i = path.lastIndexOf('/');
  277. tag = path.substr(i + 1);
  278. } else {
  279. switch (elemName) {
  280. case 'i':
  281. //italic = false;
  282. break;
  283. case 'b':
  284. //bold = false;
  285. break;
  286. case 'div':
  287. center = false;
  288. break;
  289. }
  290. }
  291. });
  292. parser.on('textNode', (text) => {// eslint-disable-line no-unused-vars
  293. if (text != ' ' && text.trim() == '')
  294. text = text.trim();
  295. if (text == '')
  296. return;
  297. switch (path) {
  298. case '/html/body/center/h2':
  299. titleInfo['book-title'] = text;
  300. return;
  301. case '/html/body/div/h3':
  302. if (!titleInfo.author)
  303. titleInfo.author = {};
  304. text = text.replace(':', '').trim().split(' ');
  305. if (text[0])
  306. titleInfo.author['last-name'] = text[0];
  307. if (text[1])
  308. titleInfo.author['first-name'] = text[1];
  309. if (text[2])
  310. titleInfo.author['middle-name'] = text[2];
  311. return;
  312. }
  313. if (inText)
  314. growParagraph(text);
  315. });
  316. parser.on('cdata', (data) => {// eslint-disable-line no-unused-vars
  317. });
  318. parser.on('comment', (text) => {// eslint-disable-line no-unused-vars
  319. if (text == '--------- Собственно произведение -------------')
  320. inText = true;
  321. if (text == '-----------------------------------------------')
  322. inText = false;
  323. });
  324. /*
  325. parser.on('progress', async(progress) => {
  326. callback(...........);
  327. });
  328. */
  329. await parser.parse(this.decode(data));
  330. const title = (titleInfo['book-title'] ? titleInfo['book-title'] : '');
  331. let author = '';
  332. if (titleInfo.author) {
  333. author = _.compact([
  334. (titleInfo.author['last-name'] ? titleInfo.author['last-name'] : ''),
  335. (titleInfo.author['first-name'] ? titleInfo.author['first-name'] : ''),
  336. (titleInfo.author['middle-name'] ? titleInfo.author['middle-name'] : ''),
  337. ]).join(' ');
  338. }
  339. pars.unshift({_n: 'title', _a: [
  340. {_n: 'p', _t: author}, {_n: 'p', _t: ''},
  341. {_n: 'p', _t: title}, {_n: 'p', _t: ''},
  342. ]})
  343. return this.formatFb2(fb2);
  344. }
  345. formatFb2(fb2) {
  346. let out = '<?xml version="1.0" encoding="utf-8"?>';
  347. out += '<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">';
  348. out += this.formatFb2Node(fb2);
  349. out += '</FictionBook>';
  350. return out;
  351. }
  352. formatFb2Node(node, name) {
  353. let out = '';
  354. if (Array.isArray(node)) {
  355. for (const n of node) {
  356. out += this.formatFb2Node(n);
  357. }
  358. } else if (typeof node == 'string') {
  359. out += `<${name}>${node}</${name}>`;
  360. } else {
  361. if (node._n)
  362. name = node._n;
  363. if (!name)
  364. throw new Error(`malformed fb2 object`);
  365. out += `<${name}>`;
  366. if (node.hasOwnProperty('_t'))
  367. out += node._t;
  368. for (let nodeName in node) {
  369. if (nodeName == '_n' || nodeName == '_t')
  370. continue;
  371. const n = node[nodeName];
  372. out += this.formatFb2Node(n, nodeName);
  373. }
  374. out += `</${name}>`;
  375. }
  376. return out;
  377. }
  378. }
  379. module.exports = BookConverter;