index.js 16 KB

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