index.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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._n == 'p' && node._a.length == 0)
  217. text = text.trimLeft();
  218. node._a.push({_t: text});
  219. };
  220. openTag('p');
  221. const onStartNode = (elemName, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  222. if (elemName == '')
  223. return;
  224. if (!inText) {
  225. path += '/' + elemName;
  226. tag = elemName;
  227. } else {
  228. if (inPara && elemName != 'i' && elemName != 'b' && elemName != 'em' && elemName != 'strong' && elemName != 'img')
  229. closeTag('p');
  230. switch (elemName) {
  231. case 'li':
  232. case 'p':
  233. case 'dd':
  234. case 'h1':
  235. case 'h2':
  236. case 'h3':
  237. case 'br':
  238. openTag('p');
  239. break;
  240. case 'i':
  241. case 'em':
  242. italic = true;
  243. break;
  244. case 'b':
  245. case 'strong':
  246. bold = true;
  247. break;
  248. case 'div':
  249. if (tail.indexOf('align="center"') >= 0) {
  250. openTag('subtitle');
  251. inSubtitle = true;
  252. }
  253. if (tail.indexOf('align="justify"') >= 0) {
  254. openTag('p');
  255. inJustify = true;
  256. }
  257. break;
  258. case 'img': {
  259. const attrs = sax.getAttrsSync(tail);
  260. if (attrs.src && attrs.src.value) {
  261. let href = attrs.src.value;
  262. if (href[0] == '/')
  263. href = `http://${hostname}${href}`;
  264. openTag('image', {href});
  265. inImage = true;
  266. }
  267. break;
  268. }
  269. }
  270. }
  271. };
  272. const onEndNode = (elemName, tail, singleTag, cutCounter, cutTag) => {// eslint-disable-line no-unused-vars
  273. if (!inText) {
  274. const oldPath = path;
  275. let t = '';
  276. do {
  277. let i = path.lastIndexOf('/');
  278. t = path.substr(i + 1);
  279. path = path.substr(0, i);
  280. } while (t != elemName && path);
  281. if (t != elemName) {
  282. path = oldPath;
  283. }
  284. let i = path.lastIndexOf('/');
  285. tag = path.substr(i + 1);
  286. } else {
  287. switch (elemName) {
  288. case 'li':
  289. case 'p':
  290. case 'dd':
  291. case 'h1':
  292. case 'h2':
  293. case 'h3':
  294. closeTag('p');
  295. break;
  296. case 'i':
  297. case 'em':
  298. italic = false;
  299. break;
  300. case 'b':
  301. case 'strong':
  302. bold = false;
  303. break;
  304. case 'div':
  305. if (inSubtitle) {
  306. closeTag('subtitle');
  307. inSubtitle = false;
  308. }
  309. if (inJustify) {
  310. closeTag('p');
  311. inJustify = false;
  312. }
  313. break;
  314. case 'img':
  315. if (inImage)
  316. closeTag('image');
  317. inImage = false;
  318. break;
  319. }
  320. }
  321. };
  322. const onComment = (text) => {// eslint-disable-line no-unused-vars
  323. if (text == '--------- Собственно произведение -------------') {
  324. inText = true;
  325. textFound = true;
  326. }
  327. if (text == '-----------------------------------------------')
  328. inText = false;
  329. };
  330. const onTextNode = (text) => {// eslint-disable-line no-unused-vars
  331. if (text != ' ' && text.trim() == '')
  332. text = text.trim();
  333. if (text == '')
  334. return;
  335. switch (path) {
  336. case '/html/body/center/h2':
  337. titleInfo['book-title'] = text;
  338. return;
  339. case '/html/body/div/h3':
  340. if (!titleInfo.author)
  341. titleInfo.author = {};
  342. text = text.replace(':', '').trim().split(' ');
  343. if (text[0])
  344. titleInfo.author['last-name'] = text[0];
  345. if (text[1])
  346. titleInfo.author['first-name'] = text[1];
  347. if (text[2])
  348. titleInfo.author['middle-name'] = text[2];
  349. return;
  350. }
  351. let tOpen = (bold ? '<strong>' : '');
  352. tOpen += (italic ? '<emphasis>' : '');
  353. let tClose = (italic ? '</emphasis>' : '');
  354. tClose += (bold ? '</strong>' : '');
  355. if (inText)
  356. growParagraph(`${tOpen}${text}${tClose}`);
  357. };
  358. sax.parseSync(repSpaces(repSpaces2(this.decode(data).toString())), {
  359. onStartNode, onEndNode, onTextNode, onComment,
  360. innerCut: new Set(['head', 'script', 'style'])
  361. });
  362. //текст не найден на странице, обрабатываем как html
  363. if (!textFound)
  364. return this.convertHtml(data);
  365. const title = (titleInfo['book-title'] ? titleInfo['book-title'] : '');
  366. let author = '';
  367. if (titleInfo.author) {
  368. author = _.compact([
  369. (titleInfo.author['last-name'] ? titleInfo.author['last-name'] : ''),
  370. (titleInfo.author['first-name'] ? titleInfo.author['first-name'] : ''),
  371. (titleInfo.author['middle-name'] ? titleInfo.author['middle-name'] : ''),
  372. ]).join(' ');
  373. }
  374. pars.unshift({_n: 'title', _a: [
  375. {_n: 'p', _t: author}, {_n: 'p', _t: ''},
  376. {_n: 'p', _t: title}, {_n: 'p', _t: ''},
  377. ]})
  378. return this.formatFb2(fb2);
  379. }
  380. formatFb2(fb2) {
  381. let out = '<?xml version="1.0" encoding="utf-8"?>';
  382. out += '<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">';
  383. out += this.formatFb2Node(fb2);
  384. out += '</FictionBook>';
  385. return out;
  386. }
  387. formatFb2Node(node, name) {
  388. let out = '';
  389. if (Array.isArray(node)) {
  390. for (const n of node) {
  391. out += this.formatFb2Node(n);
  392. }
  393. } else if (typeof node == 'string') {
  394. if (name)
  395. out += `<${name}>${repSpaces(node)}</${name}>`;
  396. else
  397. out += repSpaces(node);
  398. } else {
  399. if (node._n)
  400. name = node._n;
  401. let attrs = '';
  402. if (node._attrs) {
  403. for (let attrName in node._attrs) {
  404. attrs += ` ${attrName}="${node._attrs[attrName]}"`;
  405. }
  406. }
  407. if (name)
  408. out += `<${name}${attrs}>`;
  409. if (node.hasOwnProperty('_t'))
  410. out += repSpaces(node._t);
  411. for (let nodeName in node) {
  412. if (nodeName && nodeName[0] == '_' && nodeName != '_a')
  413. continue;
  414. const n = node[nodeName];
  415. out += this.formatFb2Node(n, nodeName);
  416. }
  417. if (name)
  418. out += `</${name}>`;
  419. }
  420. return out;
  421. }
  422. }
  423. module.exports = BookConverter;