index.js 16 KB

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