index.js 14 KB

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