index.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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 sax = require('./sax');
  7. const textUtils = require('./textUtils');
  8. const FileDetector = require('../FileDetector');
  9. const repSpaces = (text) => text.replace(/ |[\t\n\r]/g, ' ');
  10. const repSpaces2 = (text) => text.replace(/[\n\r]/g, '');
  11. const repSpaces3 = (text) => text.replace(/ /g, ' ');
  12. class BookConverter {
  13. constructor() {
  14. this.detector = new FileDetector();
  15. }
  16. async convertToFb2(inputFile, outputFile, url, callback) {
  17. const fileType = await this.detector.detectFile(inputFile);
  18. const data = await fs.readFile(inputFile);
  19. callback(100);
  20. if (fileType && (fileType.ext == 'html' || fileType.ext == 'xml')) {
  21. if (data.toString().indexOf('<FictionBook') >= 0) {
  22. await fs.writeFile(outputFile, this.checkEncoding(data));
  23. return;
  24. }
  25. const parsedUrl = new URL(url);
  26. if (parsedUrl.hostname == 'samlib.ru' ||
  27. parsedUrl.hostname == 'budclub.ru' ||
  28. parsedUrl.hostname == 'zhurnal.lib.ru') {
  29. await fs.writeFile(outputFile, this.convertSamlib(data, parsedUrl.hostname));
  30. return;
  31. }
  32. await fs.writeFile(outputFile, this.convertHtml(data));
  33. return;
  34. } else {
  35. if (fileType)
  36. throw new Error(`Этот формат файла не поддерживается: ${fileType.mime}`);
  37. else {
  38. //может это чистый текст?
  39. if (textUtils.checkIfText(data)) {
  40. await fs.writeFile(outputFile, this.convertHtml(data, true));
  41. return;
  42. }
  43. throw new Error(`Не удалось определить формат файла: ${url}`);
  44. }
  45. }
  46. }
  47. decode(data) {
  48. let selected = textUtils.getEncoding(data);
  49. if (selected == 'ISO-8859-5') {
  50. const charsetAll = chardet.detectAll(data.slice(0, 20000));
  51. for (const charset of charsetAll) {
  52. if (charset.name.indexOf('ISO-8859') < 0) {
  53. selected = charset.name;
  54. break;
  55. }
  56. }
  57. }
  58. if (selected.toLowerCase() != 'utf-8')
  59. return iconv.decode(data, selected);
  60. else
  61. return data;
  62. }
  63. checkEncoding(data) {
  64. let result = data;
  65. const left = data.indexOf('<?xml version="1.0"');
  66. if (left >= 0) {
  67. const right = data.indexOf('?>', left);
  68. if (right >= 0) {
  69. const head = data.slice(left, right + 2).toString();
  70. const m = head.match(/encoding="(.*)"/);
  71. if (m) {
  72. let encoding = m[1].toLowerCase();
  73. if (encoding != 'utf-8') {
  74. result = iconv.decode(data, encoding);
  75. result = Buffer.from(result.toString().replace(m[0], 'encoding="utf-8"'));
  76. }
  77. }
  78. }
  79. }
  80. return result;
  81. }
  82. convertHtml(data, isText) {
  83. let titleInfo = {};
  84. let desc = {_n: 'description', 'title-info': titleInfo};
  85. let pars = [];
  86. let body = {_n: 'body', section: {_a: []}};
  87. let fb2 = [desc, body];
  88. let title = '';
  89. let inTitle = false;
  90. let spaceCounter = [];
  91. const newParagraph = () => {
  92. pars.push({_n: 'p', _t: ''});
  93. };
  94. const growParagraph = (text) => {
  95. if (!pars.length)
  96. newParagraph();
  97. const l = pars.length;
  98. if (pars[l - 1]._t == '')
  99. text = text.trimLeft();
  100. pars[l - 1]._t += text;
  101. //посчитаем отступы у текста, чтобы выделить потом параграфы
  102. const lines = text.split('\n');
  103. for (let line of lines) {
  104. line = repSpaces2(line).replace(/\t/g, ' ');
  105. let l = 0;
  106. while (l < line.length && line[l] == ' ') {
  107. l++;
  108. }
  109. if (!spaceCounter[l])
  110. spaceCounter[l] = 0;
  111. spaceCounter[l]++;
  112. }
  113. };
  114. const newPara = new Set(['tr', 'br', 'br/', 'dd', 'p', 'title', '/title', 'h1', 'h2', 'h3', '/h1', '/h2', '/h3']);
  115. const onTextNode = (text, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  116. if (!cutCounter) {
  117. growParagraph(text);
  118. }
  119. if (inTitle && !title)
  120. title = text;
  121. };
  122. const onStartNode = (tag, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  123. if (!cutCounter) {
  124. if (newPara.has(tag))
  125. newParagraph();
  126. }
  127. if (tag == 'title')
  128. inTitle = true;
  129. };
  130. const onEndNode = (tag, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  131. if (tag == 'title')
  132. inTitle = false;
  133. };
  134. let buf = this.decode(data).toString();
  135. sax.parseSync(buf, {
  136. onStartNode, onEndNode, onTextNode,
  137. innerCut: new Set(['head', 'script', 'style'])
  138. });
  139. titleInfo['book-title'] = title;
  140. //подозрение на чистый текст, надо разбить на параграфы
  141. if (isText || pars.length < buf.length/2000) {
  142. let total = 0;
  143. for (let i = 0; i < spaceCounter.length; i++) {
  144. total += (spaceCounter[i] ? spaceCounter[i] : 0);
  145. }
  146. total /= 10;
  147. let i = spaceCounter.length - 1;
  148. while (i > 0 && (!spaceCounter[i] || spaceCounter[i] < total)) i--;
  149. const parIndent = (i > 0 ? i : 0);
  150. let newPars = [];
  151. const newPar = () => {
  152. newPars.push({_n: 'p', _t: ''});
  153. };
  154. const growPar = (text) => {
  155. if (!newPars.length)
  156. newPar();
  157. const l = newPars.length;
  158. newPars[l - 1]._t += text;
  159. }
  160. i = 0;
  161. for (const par of pars) {
  162. if (i > 0)
  163. newPar();
  164. i++;
  165. const lines = par._t.split('\n');
  166. for (let line of lines) {
  167. line = repSpaces2(line).replace(/\t/g, ' ');
  168. let l = 0;
  169. while (l < line.length && line[l] == ' ') {
  170. l++;
  171. }
  172. if (l >= parIndent)
  173. newPar();
  174. growPar(line.trim() + ' ');
  175. }
  176. }
  177. body.section._a[0] = newPars;
  178. } else {
  179. body.section._a[0] = pars;
  180. }
  181. //убираем лишнее
  182. for (let i = 0; i < pars.length; i++)
  183. pars[i]._t = repSpaces(pars[i]._t).trim();
  184. return this.formatFb2(fb2);
  185. }
  186. convertSamlib(data, hostname) {
  187. let titleInfo = {};
  188. let desc = {_n: 'description', 'title-info': titleInfo};
  189. let pars = [];
  190. let body = {_n: 'body', section: {_a: pars}};
  191. let fb2 = [desc, body];
  192. let inSubtitle = false;
  193. let inJustify = true;
  194. let inImage = false;
  195. let isFirstPara = false;
  196. let path = '';
  197. let tag = '';// eslint-disable-line no-unused-vars
  198. let inText = false;
  199. let textFound = false;
  200. let node = {_a: pars};
  201. let inPara = false;
  202. let italic = false;
  203. let bold = false;
  204. const openTag = (name, attrs) => {
  205. if (name == 'p')
  206. inPara = true;
  207. let n = {_n: name, _attrs: attrs, _a: [], _p: node};
  208. node._a.push(n);
  209. node = n;
  210. };
  211. const closeTag = (name) => {
  212. if (name == 'p')
  213. inPara = false;
  214. if (node._p) {
  215. const exact = (node._n == name);
  216. node = node._p;
  217. if (!exact)
  218. closeTag(name);
  219. }
  220. };
  221. const growParagraph = (text) => {
  222. if (!node._p) {
  223. if (text.trim() != '')
  224. openTag('p');
  225. else
  226. return;
  227. }
  228. if (node._n == 'p' && node._a.length == 0)
  229. text = text.trimLeft();
  230. node._a.push({_t: text});
  231. };
  232. const onStartNode = (elemName, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  233. if (elemName == '')
  234. return;
  235. if (!inText) {
  236. path += '/' + elemName;
  237. tag = elemName;
  238. } else {
  239. switch (elemName) {
  240. case 'li':
  241. case 'p':
  242. case 'dd':
  243. case 'br':
  244. if (!(inSubtitle && isFirstPara)) {
  245. if (inPara)
  246. closeTag('p');
  247. openTag('p');
  248. }
  249. isFirstPara = false;
  250. break;
  251. case 'h1':
  252. case 'h2':
  253. case 'h3':
  254. if (inPara)
  255. closeTag('p');
  256. openTag('p');
  257. bold = true;
  258. break;
  259. case 'i':
  260. case 'em':
  261. italic = true;
  262. break;
  263. case 'b':
  264. case 'strong':
  265. bold = true;
  266. break;
  267. case 'div':
  268. if (inPara)
  269. closeTag('p');
  270. if (tail.indexOf('align="center"') >= 0) {
  271. openTag('subtitle');
  272. inSubtitle = true;
  273. isFirstPara = true;
  274. }
  275. if (tail.indexOf('align="justify"') >= 0) {
  276. openTag('p');
  277. inJustify = true;
  278. }
  279. break;
  280. case 'img': {
  281. if (inPara)
  282. closeTag('p');
  283. const attrs = sax.getAttrsSync(tail);
  284. if (attrs.src && attrs.src.value) {
  285. let href = attrs.src.value;
  286. if (href[0] == '/')
  287. href = `http://${hostname}${href}`;
  288. openTag('image', {href});
  289. inImage = true;
  290. }
  291. break;
  292. }
  293. }
  294. }
  295. };
  296. const onEndNode = (elemName, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  297. if (!inText) {
  298. const oldPath = path;
  299. let t = '';
  300. do {
  301. let i = path.lastIndexOf('/');
  302. t = path.substr(i + 1);
  303. path = path.substr(0, i);
  304. } while (t != elemName && path);
  305. if (t != elemName) {
  306. path = oldPath;
  307. }
  308. let i = path.lastIndexOf('/');
  309. tag = path.substr(i + 1);
  310. } else {
  311. switch (elemName) {
  312. case 'li':
  313. case 'p':
  314. case 'dd':
  315. closeTag('p');
  316. break;
  317. case 'h1':
  318. case 'h2':
  319. case 'h3':
  320. closeTag('p');
  321. bold = false;
  322. break;
  323. case 'i':
  324. case 'em':
  325. italic = false;
  326. break;
  327. case 'b':
  328. case 'strong':
  329. bold = false;
  330. break;
  331. case 'div':
  332. if (inSubtitle) {
  333. closeTag('subtitle');
  334. inSubtitle = false;
  335. isFirstPara = false;
  336. }
  337. if (inJustify) {
  338. closeTag('p');
  339. inJustify = false;
  340. }
  341. break;
  342. case 'img':
  343. if (inImage)
  344. closeTag('image');
  345. inImage = false;
  346. break;
  347. }
  348. }
  349. };
  350. const onComment = (text) => {// eslint-disable-line no-unused-vars
  351. if (text == '--------- Собственно произведение -------------') {
  352. inText = true;
  353. textFound = true;
  354. }
  355. if (text == '-----------------------------------------------')
  356. inText = false;
  357. };
  358. const onTextNode = (text) => {// eslint-disable-line no-unused-vars
  359. if (text && text.trim() == '')
  360. text = (text.indexOf(' ') >= 0 ? ' ' : '');
  361. if (!text)
  362. return;
  363. switch (path) {
  364. case '/html/body/center/h2':
  365. titleInfo['book-title'] = text;
  366. return;
  367. case '/html/body/div/h3':
  368. if (!titleInfo.author)
  369. titleInfo.author = {};
  370. text = text.replace(':', '').trim().split(' ');
  371. if (text[0])
  372. titleInfo.author['last-name'] = text[0];
  373. if (text[1])
  374. titleInfo.author['first-name'] = text[1];
  375. if (text[2])
  376. titleInfo.author['middle-name'] = text[2];
  377. return;
  378. }
  379. let tOpen = (bold ? '<strong>' : '');
  380. tOpen += (italic ? '<emphasis>' : '');
  381. let tClose = (italic ? '</emphasis>' : '');
  382. tClose += (bold ? '</strong>' : '');
  383. if (inText)
  384. growParagraph(`${tOpen}${text}${tClose}`);
  385. };
  386. sax.parseSync(repSpaces3(this.decode(data).toString()), {
  387. onStartNode, onEndNode, onTextNode, onComment,
  388. innerCut: new Set(['head', 'script', 'style'])
  389. });
  390. //текст не найден на странице, обрабатываем как html
  391. if (!textFound)
  392. return this.convertHtml(data);
  393. const title = (titleInfo['book-title'] ? titleInfo['book-title'] : '');
  394. let author = '';
  395. if (titleInfo.author) {
  396. author = _.compact([
  397. (titleInfo.author['last-name'] ? titleInfo.author['last-name'] : ''),
  398. (titleInfo.author['first-name'] ? titleInfo.author['first-name'] : ''),
  399. (titleInfo.author['middle-name'] ? titleInfo.author['middle-name'] : ''),
  400. ]).join(' ');
  401. }
  402. pars.unshift({_n: 'title', _a: [
  403. {_n: 'p', _t: author}, {_n: 'p', _t: ''},
  404. {_n: 'p', _t: title}, {_n: 'p', _t: ''},
  405. ]})
  406. return this.formatFb2(fb2);
  407. }
  408. formatFb2(fb2) {
  409. let out = '<?xml version="1.0" encoding="utf-8"?>';
  410. out += '<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">';
  411. out += this.formatFb2Node(fb2);
  412. out += '</FictionBook>';
  413. return out;
  414. }
  415. formatFb2Node(node, name) {
  416. let out = '';
  417. if (Array.isArray(node)) {
  418. for (const n of node) {
  419. out += this.formatFb2Node(n);
  420. }
  421. } else if (typeof node == 'string') {
  422. if (name)
  423. out += `<${name}>${repSpaces(node)}</${name}>`;
  424. else
  425. out += repSpaces(node);
  426. } else {
  427. if (node._n)
  428. name = node._n;
  429. let attrs = '';
  430. if (node._attrs) {
  431. for (let attrName in node._attrs) {
  432. attrs += ` ${attrName}="${node._attrs[attrName]}"`;
  433. }
  434. }
  435. let tOpen = '';
  436. let tBody = '';
  437. let tClose = '';
  438. if (name)
  439. tOpen += `<${name}${attrs}>`;
  440. if (node.hasOwnProperty('_t'))
  441. tBody += repSpaces(node._t);
  442. for (let nodeName in node) {
  443. if (nodeName && nodeName[0] == '_' && nodeName != '_a')
  444. continue;
  445. const n = node[nodeName];
  446. tBody += this.formatFb2Node(n, nodeName);
  447. }
  448. if (name)
  449. tClose += `</${name}>`;
  450. if (attrs == '' && name == 'p' && tBody.trim() == '')
  451. out += '<empty-line/>'
  452. else
  453. out += `${tOpen}${tBody}${tClose}`;
  454. }
  455. return out;
  456. }
  457. }
  458. module.exports = BookConverter;