index.js 15 KB

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